.NET进程间“事件”

4

我有多个同一应用程序的实例正在运行。用户可以点击每个实例上的“退出”按钮来关闭它。

我想添加一个“退出全部实例”的选项,这将触发某种“事件”,通知所有应用程序实例它们应该关闭。我不需要传输任何数据与此事件一起。

在Windows中,使用C#/.NET,最好(并且最简单)的方法是什么?

2个回答

6
将经典的WM_CLOSE消息发送到所有实例...
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

谢谢。CloseMainWindow似乎是Win32的一个不错的替代方案。 - xyz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接