0

我目前在我的应用程序中有互斥锁,它只允许运行 1 个实例。我的问题是,我现在如何获取此代码,并将其转换为关闭当前正在运行的实例并允许打开一个新实例?

我要解决的问题:我的应用程序接受 args 并且需要经常使用新参数重新打开。目前,如果没有互斥锁,它可以打开无限次。我只想运行 1 个具有最新参数集的实例。

谢谢,凯文

一些代码

bool createdMutex = true;

            Mutex mutex = new Mutex(true, "VideoViewerApp", out createdMutex);

            if (createdMutex && mutex.WaitOne())
 
            {

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmVideo(args[0], args[1], args[2], args[4], args[5]));
                mutex.ReleaseMutex();

            }

mutex.close();
4

1 回答 1

2

互斥体不适用于进程间事件通知,因此无法使用互斥体关闭另一个进程。我会建议做一些类似于这个问题中推荐的事情。

我将把这两个答案组合成我用过的东西:

Process[] processes = Process.GetProcesses();
string thisProcess = Process.GetCurrentProcess().MainModule.FileName;
string thisProcessName = Process.GetCurrentProcess().ProcessName;
foreach (var 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
    process.CloseMainWindow();
}
于 2012-05-30T16:43:47.587 回答