如何检查应用程序的另一个实例是否正在运行
本文关键字:实例 另一个 是否 运行 应用程序 何检查 检查 | 更新日期: 2023-09-27 17:59:21
有人能告诉我们如何检查程序的另一个实例(例如test.exe)是否正在运行,如果是,如果有现有实例,请停止加载应用程序。
想要一些严肃的代码吗?给你。
var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
这适用于任何应用程序(任何名称),如果有另一个实例运行同一应用程序,它将变为true
。
编辑:要解决您的需求,您可以使用以下任一项:
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;
从Main方法退出该方法。。。或
if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();
这将立即终止当前加载过程。
您需要添加对系统的引用。.Count()
扩展方法的Core.dll。或者,也可以使用.Length
属性。
不确定"程序"是什么意思,但如果您想将应用程序限制为一个实例,则可以使用Mutex来确保应用程序尚未运行。
[STAThread]
static void Main()
{
Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
try
{
if (mutex.WaitOne(0, false))
{
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
MessageBox.Show("An instance of the application is already running.");
}
}
finally
{
if (mutex != null)
{
mutex.Close();
mutex = null;
}
}
}
以下是一些不错的示例应用程序。下面是一种可能的方法。
public static Process RunningInstance()
{
Process current = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName (current.ProcessName);
//Loop through the running processes in with the same name
foreach (Process process in processes)
{
//Ignore the current process
if (process.Id != current.Id)
{
//Make sure that the process is running from the exe file.
if (Assembly.GetExecutingAssembly().Location.
Replace("/", "''") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
if (MainForm.RunningInstance() != null)
{
MessageBox.Show("Duplicate Instance");
//TODO:
//Your application logic for duplicate
//instances would go here.
}
许多其他可能的方式。有关备选方案,请参阅示例。
第一个。
第二个。
Third One
编辑1:刚刚看到你的评论,你有一个控制台应用程序。这将在第二个样本中讨论。
Process静态类有一个方法GetProcessesByName(),您可以使用它来搜索正在运行的进程。只需搜索具有相同可执行文件名称的任何其他进程。
你可以试试这个
Process[] processes = Process.GetProcessesByName("processname");
foreach (Process p in processes)
{
IntPtr pFoundWindow = p.MainWindowHandle;
// Do something with the handle...
//
}