代码之家  ›  专栏  ›  技术社区  ›  Clack

单实例windows窗体应用程序以及如何获取其参考?

  •  5
  • Clack  · 技术社区  · 16 年前

    我有一个Windows窗体应用程序,它一次只允许运行一个实例。我使用Mutex实现了Singleton。应用程序必须可以从命令行启动(有或没有参数)。应用程序由脚本启动和退出。用户无法对其执行任何操作。

    bool quit = (args.Length > 0 && args[0] == "quit") ? true : false;
    using (Mutex mutex = new Mutex(false, sExeName))
    {
        if (!mutex.WaitOne(0, true)) 
        {
            if (quit)
            {
                // This is the tricky part?
                // How can I get reference to "previous" launced 
                // Windows Forms application and call it's Exit() method.
            }
        } 
        else 
        {
            if (!quit)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
    
    4 回复  |  直到 16 年前
        1
  •  6
  •   Hans Passant    16 年前
        2
  •  5
  •   Community CDub    8 年前

    Process thisProcess = Process.GetCurrentProcess();
            Process[] allProcesses = Process.GetProcessesByName(thisProcess.ProcessName);
            Process otherProcess = null;
            foreach (Process p in allProcesses )
            {
                if ((p.Id != thisProcess.Id) && (p.MainModule.FileName == thisProcess.MainModule.FileName))
                {
                    otherProcess = p;
                    break;
                }
            }
    
           if (otherProcess != null)
           {
               //note IntPtr expected by API calls.
               IntPtr hWnd = otherProcess.MainWindowHandle;
               //restore if minimized
               ShowWindow(hWnd ,1);
               //bring to the front
               SetForegroundWindow (hWnd);
           }
            else
            {
                //run your app here
            }
    

    here

        3
  •  1
  •   Tormod Fjeldskår    16 年前

    这是一个有点快速和肮脏的解决方案,你可能想改进一下:

    [STAThread]
    static void Main()
    {
        var me = Process.GetCurrentProcess();
        var otherMe = Process.GetProcessesByName(me.ProcessName).Where(p => p.Id != me.Id).FirstOrDefault();
    
        if (otherMe != null)
        {
            otherMe.Kill();
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }