.NET inter-process “events”

☆樱花仙子☆ 提交于 2019-12-10 16:01:28

问题


I have multiple instances of the same application running. The user ask can click "Quit" on each instance to shut it down.

I would like to add the choice to "Quit All Instances", which will raise some kid of "event" that notifies all instances of the application that they should close. I don't need to transport any data along with this event.

What's the best (and preferably simplest) way to do this in Windows using C#/.NET?


回答1:


Send the good'ol WM_CLOSE to all instances...

Process[] processes = Process.GetProcesses();
string thisProcess = Process.GetCurrentProcess().MainModule.FileName;
string thisProcessName = Process.GetCurrentProcess().ProcessName;
foreach (Process process in processes)
{
   // Compare process name, this will weed out most processes
   if (thisProcessName.CompareTo(process.ProcessName) != 0) continue;
   // Check the file name of the processes main module
   if (thisProcess.CompareTo(process.MainModule.FileName) != 0) continue;
   if (Process.GetCurrentProcess().Id == process.Id) 
   {
     // We don't want to commit suicide
     continue;
   }
   // Tell the other instance to die
   Win32.SendMessage(process.MainWindowHandle, Win32.WM_CLOSE, 0, 0);
}



回答2:


The System.Diagnostics.Process class has several methods you can use.

Process.GetProcessesByName will let you enumerate all instances:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx

then Process.CloseMainWindow or Process.Close will shut them down:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx http://msdn.microsoft.com/en-us/library/system.diagnostics.process.close.aspx



来源:https://stackoverflow.com/questions/1001433/net-inter-process-events

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!