方式一:
[DllImport("user32.dll ")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //根据任务栏应用程序显示的名称找相应窗口的句柄 [DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); private const int SW_RESTORE = 9; private void OpenSerialPortUtility(object sender, EventArgs e) { //遍历进程列表查找目标程序是否运行运行则前置否则启动 Process[] pList = Process.GetProcesses("."); bool b = false; foreach (Process p in pList) { if (p.ProcessName == "wpfYourSystem") { b = true; ShowWindow(p.MainWindowHandle, SW_RESTORE); //将窗口还原,如果不用此方法,缩小的窗口不能激活 break; } } if (b == false) { System.Diagnostics.Process.Start(@"C:\Users\Administrator\Desktop\9.18测试\医生端\Debug\wpfYourSystem.exe"); } }
方式二(只是唤醒程序):
[DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab); string pName = Path.GetFileNameWithoutExtension(Application.ExecutablePath);//要启动的进程名称,可以在任务管理器里查看,一般是不带.exe后缀的; Process[] temp = Process.GetProcessesByName(pName);//在所有已启动的进程中查找需要的进程; if (temp.Length > 0)//如果查找到 { IntPtr handle = temp[0].MainWindowHandle; SwitchToThisWindow(handle, true); // 激活,显示在最前 }