Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I focus a foreign window?
    primarykey
    data
    text
    <p>I have an application which may only have one instance of itself open at a time. To enforce this, I use this code:</p> <pre><code> 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. //... </code></pre> <p>It works fine. I would also like it to be able to focus the form of the already-running copy. That is, before returning, I want to bring the other instance of this application into the foreground.</p> <p>How do I do that?</p> <p>Re: SetForeGroundWindow:</p> <p>SetForeGroundWindow works, to a point:</p> <pre><code> [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; } //... </code></pre> <p>This does bring the window to the foreground if it is not minimized. Awesome. If the window IS minimized, however, it remains minimized.</p> <p>It needs to un-minimize.</p> <p>Solution via SwitchToThisWindow (Works!):</p> <pre><code> [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 ;-) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload