Winform中打开对应窗口标题的窗口
作者:互联网
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 }
标签:IntPtr,窗口,int,hWnd,标题,static,dll,public,Winform 来源: https://www.cnblogs.com/MichaelJson/p/16182098.html