1 public static class WindowsMessageHelper 2 { 3 4 public const int WM_COPYDATA = 0x004A; 5 6 [DllImport("User32.dll", EntryPoint = "SendMessage")] 7 private static extern int SendMessage 8 ( 9 IntPtr hWnd,//目标窗体句柄 10 int Msg,//WM_COPYDATA 11 int wParam,//自定义数值 12 ref COPYDATASTRUCT lParam//结构体 13 ); 14 15 [DllImport("User32.dll", EntryPoint = "FindWindow")] 16 public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 17 18 19 [DllImport("user32.dll", EntryPoint = "SendMessage")] 20 private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); 21 22 23 [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] 24 public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); 25 26 27 [DllImport("user32.dll ")] 28 private extern static int SetActiveWindow(IntPtr hwnd); 29 30 /// <summary> 31 /// 根据句柄查找进程ID 32 /// </summary> 33 /// <param name="hwnd"></param> 34 /// <param name="ID"></param> 35 /// <returns></returns> 36 [System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] 37 public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID); 38 39 40 #region 打开该程序主窗口 41 /// <summary> 42 /// 打开该程序主窗口 43 /// </summary> 44 public static void RaiseOtherProcess(Process otherProc, string windowTitle = "你打开的窗口标题") 45 { 46 var proc = Process.GetCurrentProcess(); 47 { 48 if (proc.Id != otherProc.Id) 49 { 50 var hWnd = otherProc.MainWindowHandle; 51 if (hWnd.ToInt32() == 0) 52 { 53 hWnd = FindWindow(null, windowTitle); 54 int id = -1; 55 GetWindowThreadProcessId(hWnd, out id); 56 } 57 ShowWindow(hWnd, 0); 58 ShowWindow(hWnd, 1); 59 SetActiveWindow(hWnd); 60 InteropMethods.SetForegroundWindow(hWnd); 61 //此处获取的hWnd即为之前运行程序的主窗口句柄,再使用其他函数打开窗体 62 } 63 } 64 } 65 #endregion 66 67 [StructLayout(LayoutKind.Sequential)] 68 public struct COPYDATASTRUCT 69 { 70 71 public IntPtr dwData; 72 public int cbData;//字符串长度 73 [MarshalAs(UnmanagedType.LPStr)] 74 public string lpData;//字符串 75 } 76 77 78 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构