我有多个同一应用程序的实例正在运行。用户可以点击每个实例上的“退出”按钮来关闭它。
我想添加一个“退出全部实例”的选项,这将触发某种“事件”,通知所有应用程序实例它们应该关闭。我不需要传输任何数据与此事件一起。
在Windows中,使用C#/.NET,最好(并且最简单)的方法是什么?
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);
}
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx
然后使用Process.CloseMainWindow或Process.Close命令将它们关闭:http://msdn.microsoft.com/en-us/library/system.diagnostics.process.closemainwindow.aspx http://msdn.microsoft.com/en-us/library/system.diagnostics.process.close.aspx