我有一個應用程序,一次只能打開一個本身的實例。爲了執行此操作,我使用此代碼:如何關注外國窗口?
System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
foreach (System.Diagnostics.Process p in myProcesses)
{
if (p.ProcessName == me.ProcessName)
if (p.Id != me.Id)
{
//if already running, abort this copy.
return;
}
}
//launch the application.
//...
它工作正常。我還希望它能夠集中已經運行的副本的形式。也就是說,在返回之前,我想把這個應用程序的另一個實例放到前臺。
我該怎麼做?
回覆:SetForeGroundWindow:
SetForeGroundWindow工作,到一個點:
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
//...
if (p.Id != me.Id)
{
//if already running, focus it, and then abort this copy.
SetForegroundWindow(p.MainWindowHandle);
return;
}
//...
這確實帶來窗口前臺,如果沒有最小化它。真棒。 但是,如果窗口被最小化,它將保持最小化。
它需要取消最小化。通過SwitchToThisWindow
解決方案(作品!):
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
[STAThread]
static void Main()
{
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
foreach (System.Diagnostics.Process p in myProcesses)
{
if (p.Id != me.Id)
{
SwitchToThisWindow(p.MainWindowHandle, true);
return;
}
}
//now go ahead and start our application ;-)
檢查,看看是否窗口IsIconic,如果這樣稱呼的ShowWindow http://msdn.microsoft.com/en-us/library/ms633527(VS.85).aspx 的http:// MSDN。 microsoft.com/en-us/library/ms633548(VS.85)。aspx – cmsjr 2009-01-14 20:25:51