我有一个应用程序,一次只能打开一个本身的实例。为了执行此操作,我使用此代码:如何关注外国窗口?
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