单实例窗口形成应用程序以及如何获取它的参考?

我有一个Windows窗体应用程序,当时只允许一个实例运行。 我已经使用Mutex实现了Singleton。 应用程序必须可以从命令行启动(带或不带参数)。 应用程序由脚本启动和退出。 用户不能对其采取任何行动。

因此,应用程序的目的是简单的“指标”应用程序,它将只为最终用户显示一些视觉和图形信息。 最终用户无法对其进行任何操作,只需查看即可。 它是Windows窗体应用程序,因为视觉和图形外观是相对容易的实现(你可以得到它最顶层,无边框等)。

简单地说:当有人试图用退出命令行参数运行相同的应用程序时,如何退出当前运行的应用程序?

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()); } } } 

.NET框架为此提供了非常好的通用解决方案。 查看本MSDN杂志文章的底部。 使用StartupNextInstanceHandler()事件处理程序将任意命令传递给正在运行的实例,如“quit”。

这不是复杂的事情吗? 您是否可以重新激活现有实例,而不是关闭现有实例并启动新实例? 无论哪种方式围绕下面的代码应该给你一些关于如何去做的想法…?

 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 } 

这里有另一个问题

这是一个有点快速和肮脏的解决方案,您可能希望改进:

 [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()); } } 

如果应用程序的某个实例已经启动,则该进程将被终止; 否则应用程序正常启动。

我认为最简单的方法如下

看到链接

http://codenicely.blogspot.com/2010/04/creating-forms-object.html