Tôi có một ứng dụng mà chỉ có thể có một thể hiện của chính nó mở tại một thời điểm. Để thực thi điều này, tôi sử dụng mã này:Làm thế nào để tập trung vào một cửa sổ nước ngoài?
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.
//...
Nó hoạt động tốt. Tôi cũng muốn nó có thể tập trung vào hình thức của bản sao đã chạy. Đó là, trước khi trở về, tôi muốn đưa ví dụ khác của ứng dụng này vào nền trước.
Tôi làm như thế nào?
Re: SetForegroundWindow:
SetForegroundWindow hoạt động, đến một điểm:
[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;
}
//...
này mang lại các cửa sổ để foreground nếu nó không được giảm thiểu. Tuyệt vời. Nếu cửa sổ IS được thu nhỏ, tuy nhiên, nó vẫn được thu nhỏ.
Nó cần phải giảm thiểu.
Solution qua SwitchToThisWindow (trình!):
[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 ;-)
Kiểm tra xem cửa sổ IsIconic, nếu có thì gọi ShowWindow http://msdn.microsoft.com/en-us/library/ms633527(VS.85).aspx http: // MSDN. microsoft.com/en-us/library/ms633548(VS.85).aspx – cmsjr