OnScreenKeyboardClass.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using System.Threading.Tasks;
  5. namespace CCDCount.DLL.Tools
  6. {
  7. public static class OnScreenKeyboard
  8. {
  9. [DllImport("user32.dll", SetLastError = true)]
  10. static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  11. [DllImport("user32.dll")]
  12. static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  13. [DllImport("user32.dll")]
  14. static extern bool SetForegroundWindow(IntPtr hWnd);
  15. [DllImport("user32.dll")]
  16. static extern bool IsWindowVisible(IntPtr hWnd);
  17. const int SW_SHOW = 5;
  18. const int SW_RESTORE = 9;
  19. const int SW_HIDE = 0;
  20. public static async void Show()
  21. {
  22. // 查找现有窗口
  23. IntPtr keyboardWnd = FindWindow("IPTip_Main_Window", null);
  24. // 首先确保没有旧进程
  25. KillTabTipProcess();
  26. // 等待进程完全终止
  27. await Task.Delay(300);
  28. // 启动新实例
  29. if (StartNewInstance())
  30. {
  31. // 等待窗口出现(使用循环检测,而非固定延迟)
  32. for (int i = 0; i < 10; i++)
  33. {
  34. await Task.Delay(200);
  35. keyboardWnd = FindWindow("IPTip_Main_Window", null);
  36. if (keyboardWnd != IntPtr.Zero) break;
  37. }
  38. if (keyboardWnd != IntPtr.Zero)
  39. {
  40. ShowWindow(keyboardWnd, SW_RESTORE);
  41. SetForegroundWindow(keyboardWnd);
  42. }
  43. }
  44. }
  45. private static bool StartNewInstance()
  46. {
  47. try
  48. {
  49. string[] keyboardPaths = {
  50. @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe",
  51. @"C:\Program Files (x86)\Common Files\Microsoft Shared\ink\TabTip.exe"
  52. };
  53. foreach (string path in keyboardPaths)
  54. {
  55. if (System.IO.File.Exists(path))
  56. {
  57. Process.Start(new ProcessStartInfo
  58. {
  59. FileName = path,
  60. UseShellExecute = true
  61. });
  62. return true;
  63. }
  64. }
  65. }
  66. catch
  67. {
  68. // 启动失败
  69. }
  70. return false;
  71. }
  72. public static void Hide()
  73. {
  74. IntPtr keyboardWnd = FindWindow("IPTip_Main_Window", null);
  75. if (keyboardWnd != IntPtr.Zero)
  76. {
  77. ShowWindow(keyboardWnd, SW_HIDE);
  78. }
  79. KillTabTipProcess();
  80. }
  81. public static void KillTabTipProcess()
  82. {
  83. try
  84. {
  85. Process[] processes = Process.GetProcessesByName("TabTip");
  86. foreach (Process process in processes)
  87. {
  88. process.Kill();
  89. process.WaitForExit();
  90. }
  91. }
  92. catch
  93. {
  94. // 忽略异常
  95. }
  96. }
  97. }
  98. }