當有人將此代碼作爲running only a single instance of an application的解決方案低估時沒有說明他們爲什麼這樣做,所以很好奇。確保使用WINAPI的應用程序的單個實例?
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 2012-03-15 19:15:43
@SLaks:只是爲了測試其他實例是否正在關閉。 – 2012-03-15 19:17:13
@opatachibueze:咦?不,它沒有。 – SLaks 2012-03-15 19:18:18