韩言福地

只有想不到的,没有办不到的。 - HY Auspicious Place

« 命运 如何改变启动子进程,等待子进程结束,并获得输出 »

让Windows程序只启动一个实例,第二个实例启动激活第一个实例

      

和网上的一些不大一样,没有用2个函数,一次就高定了.

如果你的窗体,没有出现在任务栏讲无法激活,在这个问题上找了好久原因...

 

  [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);

static void Main()
        {

            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历与当前进程名称相同的进程列表
            foreach (Process process in processes)
            {
                //Ignore the current process
                if (process.Id != current.Id)
                {
                    //Make sure that the process is running from the exe file.
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        ShowWindowAsync(process.MainWindowHandle, 1); //调用api函数,正常显示窗口
                        SetForegroundWindow(process.MainWindowHandle); //将窗口放置最前端。
                        return;
                    }
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

        }

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

最新评论及回复

最近发表

Copyright 2007-2010 www.yinrg.com(HY Auspicious Place) . 湘ICP备06007796号.