C#调用Windows系统自带虚拟键盘的方法

C#调用Windows系统自带虚拟键盘,可以通过以下方法。

1、添加外部引用

private const Int32 WM_SYSCOMMAND = 274;
    private const UInt32 SC_CLOSE = 61536;
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam);
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int RegisterWindowMessage(string lpString);

打开虚拟键盘方法:

public  void ShowKey()
    {

        var commonFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);
        //程序集目标平台为X86时,获取到的是x86的Program Files,但TabTip.exe始终在Program Files目录下
        if (commonFilesPath.Contains("Program Files (x86)"))
        {
            commonFilesPath = commonFilesPath.Replace("Program Files (x86)", "Program Files");
        }

        var tabTipPath = Path.Combine(commonFilesPath, @"microsoft shared\ink\TabTip.exe");
        //var tabTipPath = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";
        if (File.Exists(tabTipPath))
        {
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = tabTipPath,
                UseShellExecute = true,
                CreateNoWindow = true
            };
            Process.Start(psi);
            //Process.Start(@"C:\windows\system32\osk.exe");
            UnityEngine.Debug.Log("OK");
        }
    }

关闭键盘方法:

 public  void HideKey()
    {
        IntPtr TouchhWnd = new IntPtr(0);
        TouchhWnd = FindWindow("IPTip_Main_Window", null);
        if (TouchhWnd == IntPtr.Zero)
            return;
        PostMessage(TouchhWnd, WM_SYSCOMMAND, SC_CLOSE, 0);
    }

经测试使用该方法调用win8/10系统都没问题。

实现效果:

Unity通过调用win自带虚拟键盘签名

你可能感兴趣的:(c#,windows,unity)