我目前正在开发一个简单的转换器工具,并且想知道如果再次运行.exe,是否可以关闭应用程序。某种“如果两个实例运行 - >关闭两者”。
我需要这个功能,因为我通过第三方程序内的快捷按钮运行应用程序。所以,如果我再次按下此快捷按钮,我希望转换器应用程序关闭。
我知道这听起来很反直接运行exe关闭,但我必须让我的应用程序与第三方程序中的集成工具一样工作,这涉及通过按下各自的切换来打开和关闭工具 - 纽扣。我无法添加在第三方程序中运行的插件,但我可以在集成工具旁边添加一个快捷按钮。这是一个解决方法,但它至少会像切换按钮一样。
答案 0 :(得分:1)
我在这个问题中推荐MUTEX答案: How can I prevent launching my app multiple times?
虽然MUTEX答案标识了第二个实例,但它无法找到它并告诉它关闭。
解决方案:在应用程序中监听命名管道(第一个例子是ClosEE):
//using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public static class SomeClass
{
public static void SomeMethod()
{
Threading.Thread t = new Threading.Thread(() =>
{
try {
while (true) {
dynamic server = new NamedPipeServerStream("Closer", PipeDirection.InOut, -1);
server.WaitForConnection();
if (!server.IsConnected)
return;
dynamic reader = new IO.StreamReader(server);
dynamic casetxt = reader.ReadToEnd();
server.Close();
RootForm.Invoke(() =>
{
if (casetxt == "End") {
System.Environment.Exit(0);
}
});
}
} catch (Exception ex) {
// try/catch required in all child threads as error silently ends app.
// log it...
}
});
t.IsBackground = true;
t.Name = "EnderListener";
t.Start();
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
然后当你通过Mutex检测到第二个实例时,从第二个实例发送此消息“Closer”:
dynamic serverloopcount = 1;
dynamic iteration = 1;
dynamic GotServerCount = false;
do {
NamedPipeClientStream client = new NamedPipeClientStream("Closer");
client.Connect();
if (!GotServerCount) {
GotServerCount = true;
serverloopcount = client.NumberOfServerInstances;
}
dynamic reader = new IO.StreamReader(client);
dynamic writer = new IO.StreamWriter(client);
writer.WriteLine("End");
writer.Flush();
writer.Close();
client.Close();
iteration += 1;
} while (iteration <= serverloopcount);
祝你好运。
答案 1 :(得分:1)
你可以这样做:
Process currentProcess = Process.GetCurrentProcess();
bool suocide = false;
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.MainModule.FileName == currentProcess.MainModule.FileName && process.Id != currentProcess.Id)
{
process.CloseMainWindow();
process.Close();
//process.Kill(); or you can do kill instead
suocide = true;
}
}
if (suocide)
currentProcess.Kill(); // you probably don't care about new process as it is just for closing purpose but if you do then do a proper application exit
您可以将它放在窗口构造函数中。