在 Windows 8 和 Windows 10 上显示触摸键盘

针对 .NET Framework 4.6.2 及更高版本的 WPF 应用程序

使用面向 .NET Framework 4.6.2(及更高版本)的 WPF 应用程序,软键盘会自动调用和解除,无需任何其他步骤。

https://i.stack.imgur.com/m8jUb.gif

针对 .NET Framework 4.6.1 及更早版本的 WPF 应用程序

WPF 主要不是触摸启用,这意味着当用户与桌面上的 WPF 应用程序交互时,当 TextBox 控件获得焦点时,应用程序将不会自动显示触摸键盘。这对于平板电脑用户来说是一种不方便的行为,迫使他们通过系统任务栏手动打开触摸键盘。

https://i.stack.imgur.com/nFKN1.jpg

解决方法

触摸键盘实际上是一个经典的 exe 应用程序,可以在以下路径上的每台 Windows 8 和 Windows 10 PC 上找到:C:\Program Files\Common Files\Microsoft Shared\Ink\TabTip.exe

基于这些知识,你可以创建一个自定义控件,该控件派生自 TextBox,它监听 GotTouchCapture 事件(当控件通过触摸获得焦点时调用此事件)并启动触摸键盘的过程

public class TouchEnabledTextBox : TextBox
{
    public TouchEnabledTextBox()
    {
        this.GotTouchCapture += TouchEnabledTextBox_GotTouchCapture;
    }

    private void TouchEnabledTextBox_GotTouchCapture(
       object sender, 
       System.Windows.Input.TouchEventArgs e )
    {
        string touchKeyboardPath =
           @"C:\Program Files\Common Files\Microsoft Shared\Ink\TabTip.exe";        
        Process.Start( touchKeyboardPath );
    }
}

你可以通过缓存创建的进程进一步改进,然后在控件失去焦点后将其终止:

//added field
private Process _touchKeyboardProcess = null;
 
//replace Process.Start line from the previous listing with
_touchKeyboardProcess = Process.Start( touchKeyboardPath );

现在你可以连接 LostFocus 事件:

//add this at the end of TouchEnabledTextBox's constructor
this.LostFocus += TouchEnabledTextBox_LostFocus;

//add this method as a member method of the class
private void TouchEnabledTextBox_LostFocus( object sender, RoutedEventArgs eventArgs ){
   if ( _touchKeyboardProcess != null ) 
   {
      _touchKeyboardProcess.Kill();
      //nullify the instance pointing to the now-invalid process
      _touchKeyboardProcess = null;
   }
}

请注意 Windows 10 中的 Tablet 模式

Windows 10 引入了平板电脑模式,在以触摸优先方式使用 PC 时简化了与系统的交互。除了其他改进之外,此模式还可确保即使是经典桌面应用程序(包括 WPF 应用程序)也能自动显示触摸键盘

Windows 10 设置方法

除平板电脑模式外,Windows 10 还可以在平板电脑模式之外自动显示经典应用的触控键盘。默认情况下禁用的此行为可以在设置应用中启用。

在“ 设置” 应用中,转到“ 设备” 类别,然后选择“ 键入” 。如果你完全向下滚动,则可以找到不在平板电脑模式下显示触摸键盘或手写面板且没有连接键盘设置,你可以启用该设置。

StackOverflow 文档

值得一提的是,此设置仅在具有触摸功能的设备上可见。