using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace CCDCount.DLL.Tools { public static class OnScreenKeyboard { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hWnd); const int SW_SHOW = 5; const int SW_RESTORE = 9; const int SW_HIDE = 0; public static async void Show() { // 首先确保没有旧进程 KillTabTipProcess(); // 等待进程完全终止 await Task.Delay(300); // 启动新实例 if (StartNewInstance()) { // 等待窗口出现 await Task.Delay(500); IntPtr keyboardWnd = FindWindow("IPTip_Main_Window", null); if (keyboardWnd != IntPtr.Zero) { ShowWindow(keyboardWnd, SW_RESTORE); SetForegroundWindow(keyboardWnd); } } } private static async Task ShowKeyboardAsync() { // 尝试查找已运行的键盘实例 IntPtr keyboardWnd = FindWindow("IPTip_Main_Window", null); if (keyboardWnd != IntPtr.Zero && IsWindowVisible(keyboardWnd)) { // 键盘已经在显示中 SetForegroundWindow(keyboardWnd); return; } // 尝试使用COM接口 if (TryShowWithCom()) return; // 启动新实例 if (StartNewInstance()) { // 等待窗口出现 await Task.Delay(300); keyboardWnd = FindWindow("IPTip_Main_Window", null); } // 显示窗口 if (keyboardWnd != IntPtr.Zero) { ShowWindow(keyboardWnd, SW_RESTORE); SetForegroundWindow(keyboardWnd); } } private static bool TryShowWithCom() { try { Type type = Type.GetTypeFromProgID("TabTip.TabTip"); if (type != null) { object instance = Activator.CreateInstance(type); type.InvokeMember("Show", System.Reflection.BindingFlags.InvokeMethod, null, instance, null); Marshal.ReleaseComObject(instance); return true; } } catch { // COM方法失败,继续尝试其他方法 } return false; } private static bool StartNewInstance() { try { string[] keyboardPaths = { @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe", @"C:\Program Files (x86)\Common Files\Microsoft Shared\ink\TabTip.exe" }; foreach (string path in keyboardPaths) { if (System.IO.File.Exists(path)) { Process.Start(new ProcessStartInfo { FileName = path, UseShellExecute = true }); return true; } } } catch { // 启动失败 } return false; } public static void Hide() { IntPtr keyboardWnd = FindWindow("IPTip_Main_Window", null); if (keyboardWnd != IntPtr.Zero) { ShowWindow(keyboardWnd, SW_HIDE); } KillTabTipProcess(); } public static void KillTabTipProcess() { try { Process[] processes = Process.GetProcessesByName("TabTip"); foreach (Process process in processes) { process.Kill(); process.WaitForExit(); } } catch { // 忽略异常 } } } }