C#实现打开另一个程序并前置显示


        [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)
        {


           //第一种方法

            //查找状态中的窗口线程句柄来查看目标程序是否在运行运行则前置否则打开
            IntPtr findPtr = FindWindow(null, "友善串口调试助手");
            if (findPtr.ToInt32() != 0)
            {
                ShowWindow(findPtr, SW_RESTORE); //将窗口还原,如果不用此方法,缩小的窗口不能激活
                SetForegroundWindow(findPtr);//将指定的窗口选中(激活)
            }
            else
            {
                System.Diagnostics.Process.Start(@"D:\Program Files (x86)\Serial Port Utility\SerialPortUtility.exe");
            }

    //第二种方法
            //遍历进程列表查找目标程序是否运行运行则前置否则启动
            //Process[] pList = Process.GetProcesses(".");
            //bool b = false;
            //foreach (Process p in pList)
            //{
            //    if (p.ProcessName == "SerialPortUtility")
            //    {
            //        b = true;
            //        //Process.GetCurrentProcess();
            //        ShowWindow(p.MainWindowHandle, SW_RESTORE); //将窗口还原,如果不用此方法,缩小的窗口不能激活
            //        bool res = SetForegroundWindow(p.MainWindowHandle);
            //        if (res == false)
            //        {

            //        }
            //        break;
            //    }
            //}
            //if (b == false)
            //{
            //    System.Diagnostics.Process.Start(@"D:\Program Files (x86)\Serial Port Utility\SerialPortUtility.exe");
            //}
        }
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页