使用全局类型获取焦点事件
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));EventManager.RegisterClassHandler(typeof(TextBox), TextBox.LostFocusEvent, new RoutedEventHandler(TextBox_LostFocus));private void TextBox_GotFocus(object sender, RoutedEventArgs e){//获取焦点打开键盘}private void TextBox_LostFocus(object sender, RoutedEventArgs e){//失去焦点关闭键盘}
NuGet包:Microsoft.Xaml.Behaviors.Wpf
using Microsoft.Xaml.Behaviors;
using System.Diagnostics;
using System.Windows.Controls;public class ShowTouchKeyboardBehavior : Behavior<TextBox>
{protected override void OnAttached(){base.OnAttached();AssociatedObject.GotFocus += AssociatedObject_GotFocus;AssociatedObject.PreviewMouseDown += AssociatedObject_PreviewMouseDown;}protected override void OnDetaching(){base.OnDetaching();AssociatedObject.GotFocus -= AssociatedObject_GotFocus;AssociatedObject.PreviewMouseDown -= AssociatedObject_PreviewMouseDown;}private void AssociatedObject_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e){ShowTouchKeyboard();}private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e){ShowTouchKeyboard();}private void ShowTouchKeyboard(){try{Process.Start(new ProcessStartInfo{FileName = "cmd.exe",Arguments = "/c start tabtip:",WindowStyle = ProcessWindowStyle.Hidden,CreateNoWindow = true});}catch{// 备用方案try{Process.Start("osk.exe");}catch { }}}
}
在XAML中使用:
<Window x:Class="YourNamespace.MainWindow"xmlns:behaviors="clr-namespace:YourNamespace"><Grid><TextBox Width="200" Height="30"><i:Interaction.Behaviors><behaviors:ShowTouchKeyboardBehavior/></i:Interaction.Behaviors></TextBox><PasswordBox Width="200" Height="30" Margin="0,40,0,0"><i:Interaction.Behaviors><behaviors:ShowTouchKeyboardBehavior/></i:Interaction.Behaviors></PasswordBox></Grid>
</Window>
或者另外一种xaml附加法
public static class TouchKeyboardHelper
{public static readonly DependencyProperty EnableTouchKeyboardProperty =DependencyProperty.RegisterAttached("EnableTouchKeyboard", typeof(bool), typeof(TouchKeyboardHelper),new PropertyMetadata(false, OnEnableTouchKeyboardChanged));public static void SetEnableTouchKeyboard(UIElement element, bool value)=> element.SetValue(EnableTouchKeyboardProperty, value);public static bool GetEnableTouchKeyboard(UIElement element)=> (bool)element.GetValue(EnableTouchKeyboardProperty);private static void OnEnableTouchKeyboardChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){if (d is Control control){if ((bool)e.NewValue)control.GotFocus += Control_GotFocus;elsecontrol.GotFocus -= Control_GotFocus;}}private static void Control_GotFocus(object sender, RoutedEventArgs e){string tabTipPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";if (File.Exists(tabTipPath) && Process.GetProcessesByName("TabTip").Length == 0)Process.Start(tabTipPath);}
}
XAML里如下使用
<TextBox Width="200"Height="40"local:TouchKeyboardHelper.EnableTouchKeyboard="True" />