【发布时间】:2012-03-15 19:12:26
【问题描述】:
当有人拒绝将此代码作为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);
有人可以向我解释这种方法的缺点吗?谢谢。
【问题讨论】:
-
Process.GetCurrentProcess().WaitForExit... 什么? -
@SLaks:只是为了测试其他实例是否正在关闭。
-
@opatachibueze:嗯?不,它没有。
-
@SLaks:哦,天哪。我现在看到了...忘记了 showwindow 和 setforegroundwindow 返回 bool,因此尝试捕获。这很有趣,虽然我写了很长时间。