OnScreenKeyboardClass.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace CCDCount.DLL.Tools
  9. {
  10. public static class OnScreenKeyboard
  11. {
  12. [DllImport("kernel32.dll")]
  13. private static extern IntPtr GetModuleHandle(string lpModuleName);
  14. [DllImport("user32.dll")]
  15. private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
  16. [DllImport("user32.dll")]
  17. private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
  18. [DllImport("user32.dll")]
  19. private static extern bool SetForegroundWindow(IntPtr hWnd);
  20. [DllImport("user32.dll")]
  21. private static extern bool IsIconic(IntPtr hWnd);
  22. private const int SW_SHOW = 5;
  23. private const int SW_RESTORE = 9;
  24. private const int SW_HIDE = 0;
  25. /// <summary>
  26. /// 启动软键盘(兼容Windows 10及以上版本)
  27. /// </summary>
  28. public static void KeyBoardShow()
  29. {
  30. //// 检查是否为Windows 10或更高版本
  31. //if (IsWindows10OrHigher())
  32. //{
  33. // // 尝试启动TabTip
  34. // if (TryStartTabTip())
  35. // return;
  36. //}
  37. // 回退到传统osk
  38. //StartOnScreenKeyboardRobust();
  39. StartOnScreenKeyboard();
  40. }
  41. /// <summary>
  42. /// 隐藏软键盘
  43. /// </summary>
  44. public static void KeyBoardHide()
  45. {
  46. try
  47. {
  48. // 隐藏TabTip窗口
  49. //IntPtr tabTipHwnd = FindWindow("IPTip_Main_Window", null);
  50. //if (tabTipHwnd != IntPtr.Zero)
  51. //{
  52. // ShowWindow(tabTipHwnd, SW_HIDE);
  53. //}
  54. // 隐藏OSK窗口
  55. IntPtr oskHwnd = FindWindow("OSKMainClass", "屏幕键盘");
  56. if (oskHwnd != IntPtr.Zero)
  57. {
  58. ShowWindow(oskHwnd, SW_HIDE);
  59. }
  60. }
  61. catch
  62. {
  63. // 忽略异常
  64. }
  65. }
  66. private static void StartOnScreenKeyboard()
  67. {
  68. try
  69. {
  70. // 检查是否已经运行
  71. Process[] oskProcesses = Process.GetProcessesByName("osk");
  72. if (oskProcesses.Length > 0)
  73. {
  74. Console.WriteLine("进入了分支");
  75. // 如果已经运行,尝试显示窗口
  76. IntPtr oskHwnd = FindWindow("OSKMainClass", "屏幕键盘");
  77. if (oskHwnd != IntPtr.Zero)
  78. {
  79. // 【修改点】:判断是否最小化
  80. if (IsIconic(oskHwnd))
  81. {
  82. // 如果最小化,使用 SW_RESTORE (9) 恢复窗口
  83. ShowWindow(oskHwnd, SW_RESTORE);
  84. }
  85. else
  86. {
  87. // 如果未最小化,使用 SW_SHOW (5) 显示/激活
  88. ShowWindow(oskHwnd, SW_SHOW);
  89. }
  90. // 确保窗口前置
  91. SetForegroundWindow(oskHwnd);
  92. return;
  93. }
  94. else
  95. {
  96. // 如果找不到窗口,杀死进程重新启动
  97. foreach (var process in oskProcesses)
  98. {
  99. try { process.Kill(); } catch { }
  100. }
  101. }
  102. }
  103. Console.WriteLine("执行开启软键盘");
  104. Process.Start(Path.Combine(Environment.SystemDirectory, "osk.exe"));
  105. }
  106. catch (Exception ex)
  107. {
  108. throw new InvalidOperationException("无法启动屏幕键盘", ex);
  109. }
  110. }
  111. /// <summary>
  112. /// 健壮的 OSK 启动方法
  113. /// </summary>
  114. private static void StartOnScreenKeyboardRobust()
  115. {
  116. try
  117. {
  118. // 1. 彻底清理已存在的 osk 进程,防止句柄冲突
  119. KillOskProcess();
  120. // 2. 准备启动信息
  121. string oskPath = Path.Combine(Environment.SystemDirectory, "osk.exe");
  122. if (!File.Exists(oskPath))
  123. {
  124. throw new FileNotFoundException("未找到 osk.exe", oskPath);
  125. }
  126. ProcessStartInfo startInfo = new ProcessStartInfo
  127. {
  128. FileName = oskPath,
  129. UseShellExecute = true, // 关键:使用 Shell 执行,有助于权限处理
  130. Verb = "open"
  131. };
  132. // 3. 启动进程
  133. Process proc = Process.Start(startInfo);
  134. // 4. 等待窗口出现并激活
  135. // osk.exe 启动较慢,需要轮询等待窗口句柄
  136. IntPtr hwnd = IntPtr.Zero;
  137. int retryCount = 0;
  138. const int maxRetries = 50; // 最多等待 5秒 (50 * 100ms)
  139. while (retryCount < maxRetries)
  140. {
  141. // 查找窗口类名 OSKMainClass,标题可能是 "屏幕键盘" 或 "On-Screen Keyboard" (取决于系统语言)
  142. hwnd = FindWindow("OSKMainClass", null);
  143. if (hwnd != IntPtr.Zero)
  144. {
  145. break;
  146. }
  147. Thread.Sleep(100);
  148. retryCount++;
  149. }
  150. if (hwnd != IntPtr.Zero)
  151. {
  152. // 确保窗口不是最小化状态
  153. if (IsIconic(hwnd))
  154. {
  155. ShowWindow(hwnd, SW_RESTORE);
  156. }
  157. else
  158. {
  159. ShowWindow(hwnd, SW_SHOW);
  160. }
  161. // 尝试将窗口前置
  162. SetForegroundWindow(hwnd);
  163. }
  164. else
  165. {
  166. System.Diagnostics.Debug.WriteLine("警告: OSK 进程已启动,但未检测到窗口句柄。可能需要管理员权限。");
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. System.Diagnostics.Debug.WriteLine($"启动 OSK 失败: {ex.Message}");
  172. // 在生产环境中,建议记录日志而不是直接抛出异常,以免崩溃主程序
  173. }
  174. }
  175. /// <summary>
  176. /// 强制杀死所有 osk 进程
  177. /// </summary>
  178. private static void KillOskProcess()
  179. {
  180. try
  181. {
  182. Process[] processes = Process.GetProcessesByName("osk");
  183. foreach (var p in processes)
  184. {
  185. try
  186. {
  187. if (!p.HasExited)
  188. {
  189. p.Kill();
  190. p.WaitForExit(1000); // 等待进程完全退出
  191. }
  192. }
  193. catch { }
  194. }
  195. }
  196. catch { }
  197. }
  198. private static bool IsWindows10OrHigher()
  199. {
  200. var os = Environment.OSVersion;
  201. if (os.Version.Major >= 10)
  202. return true;
  203. try
  204. {
  205. using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
  206. {
  207. var currentBuild = key?.GetValue("CurrentBuild")?.ToString();
  208. if (int.TryParse(currentBuild, out int buildNumber))
  209. {
  210. // Windows 10 build 10240及以上
  211. return buildNumber >= 10240;
  212. }
  213. }
  214. }
  215. catch
  216. {
  217. // 忽略异常
  218. }
  219. // 兼容性检查:Windows 8.1及以后版本的Major是6,但Minor版本不同
  220. return os.Version.Major == 10 || (os.Version.Major == 6 && os.Version.Minor >= 2);
  221. }
  222. private static bool TryStartTabTip()
  223. {
  224. try
  225. {
  226. // 检查是否已经运行
  227. Process[] tabTipProcesses = Process.GetProcessesByName("TabTip");
  228. if (tabTipProcesses.Length > 0)
  229. {
  230. // 如果找不到窗口,杀死进程重新启动
  231. foreach (var process in tabTipProcesses)
  232. {
  233. try { process.Kill(); } catch { }
  234. }
  235. }
  236. // 方法1:通过注册表查找路径
  237. string tabTipPath = GetTabTipPathFromRegistry();
  238. if (!string.IsNullOrEmpty(tabTipPath) && File.Exists(tabTipPath))
  239. {
  240. Process.Start(tabTipPath);
  241. return true;
  242. }
  243. // 方法2:通过系统路径查找
  244. string systemPath = Path.Combine(Environment.SystemDirectory, "TabTip.exe");
  245. if (File.Exists(systemPath))
  246. {
  247. Process.Start(systemPath);
  248. return true;
  249. }
  250. // 方法3:使用modern Windows 10路径
  251. string modernPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),
  252. @"TabletTip\1.7\TabTip.exe");
  253. if (File.Exists(modernPath))
  254. {
  255. Process.Start(modernPath);
  256. return true;
  257. }
  258. // 方法4:使用默认路径
  259. string defaultPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
  260. if (File.Exists(defaultPath))
  261. {
  262. Process.Start(defaultPath);
  263. return true;
  264. }
  265. }
  266. catch (Exception ex)
  267. {
  268. // 记录异常但不中断
  269. System.Diagnostics.Debug.WriteLine($"启动TabTip失败: {ex.Message}");
  270. }
  271. return false;
  272. }
  273. private static string GetTabTipPathFromRegistry()
  274. {
  275. try
  276. {
  277. using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\InboxApplications"))
  278. {
  279. if (key != null)
  280. {
  281. foreach (var subKeyName in key.GetSubKeyNames())
  282. {
  283. if (subKeyName.Contains("Microsoft.Windows.Keyboard"))
  284. {
  285. using (var subKey = key.OpenSubKey(subKeyName))
  286. {
  287. var installPath = subKey?.GetValue("Path")?.ToString();
  288. if (!string.IsNullOrEmpty(installPath))
  289. {
  290. string tabTipPath = Path.Combine(installPath, "TabTip.exe");
  291. if (File.Exists(tabTipPath))
  292. return tabTipPath;
  293. }
  294. }
  295. }
  296. }
  297. }
  298. }
  299. }
  300. catch
  301. {
  302. // 忽略注册表访问异常
  303. }
  304. return null;
  305. }
  306. }
  307. }