Ich habe eine Anwendung, die nur eine Instanz von sich selbst geöffnet haben kann. Um dies zu erzwingen, verwende ich diesen Code:Wie fokussiere ich ein fremdes Fenster?
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.
//...
Es funktioniert gut. Ich möchte auch, dass es in der Lage ist, die Form der bereits laufenden Kopie zu fokussieren. Bevor ich zurückkomme, möchte ich die andere Instanz dieser Anwendung in den Vordergrund bringen.
Wie mache ich das?
Re: SetForegroundWindow:
SetForegroundWindow arbeitet, bis zu einem Punkt:
[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;
}
//...
Dieses aus dem Fenster in den Vordergrund bringt, wenn es nicht minimiert wird. Genial. Wenn das Fenster minimiert ist, bleibt es minimiert.
Es muss nicht minimiert werden.
Lösung über SwitchToThisWindow (Works!):
[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 ;-)
Überprüfen Sie, ob das Fenster IsIconic, wenn so nennen Showwindow http://msdn.microsoft.com/en-us/library/ms633527(VS.85).aspx http: // msdn. microsoft.com/en-us/library/ms633548(VS.85).aspx – cmsjr