使用WINAPI确保应用程序的单个实例?

时间:2012-03-15 19:12:27

标签: c# winapi mutex

当有人将这段代码作为running only a single instance of an application的解决方案进行投票而没有说明他们为什么会这样做时,我很好奇。

 int hWnd = FindWindow(null, "My Application Title");
 if (hWnd > 0) //If found
 {
     Process.GetCurrentProcess().WaitForExit(600);
     try
     {
        SetForegroundWindow(hWnd); //Activate it
        ShowWindow(hWnd, 9);
        Process.GetCurrentProcess().Kill();
     }
     catch (Exception ex)
     {
        //write to log
     }
 }

 //Import the FindWindow API to find our window
 [DllImport("User32.dll")]
 public static extern int FindWindow(String ClassName, String WindowName);
 //Import the SetForeground API to activate it
 [DllImport("User32.dll")]
 public static extern IntPtr SetForegroundWindow(int hWnd);
 //Import the ShowWindow API to show it
 [DllImport("User32.dll")]
 public static extern bool ShowWindow(int hWnd, int nCmdShow);

有人可以向我解释这种方法的缺点吗?感谢。

2 个答案:

答案 0 :(得分:4)

因为如果应用程序启动两次(意外点击),则会有一个小的时间窗口,测试将失败。这两个实例都可能正在启动但尚未创建窗口。

答案 1 :(得分:1)

据我所知,缺点是它应该是一个简单的解决方案过于复杂。你不需要破解windows api来强制api的单个实例。我猜这就是你投票的原因。

如果您按照Uwe的答案中的链接进行操作,您将看到您可以保留托管代码,这应该是您的默认代码,除非您有某种原因必须深入挖掘。

相关问题