107

How to bring my application window to front? For example whan my app needs attention.

This is for my personal program. I need that functionality.

This is what I got. But it's NOT working 100% times.

public void BringToFrontToEnterCaptha()
{
    if (InvokeRequired)
    {
        Invoke(new Action(BringToFrontToEnterCaptha));
    }
    else
    {
        this.TopMost = true;
        this.Focus();
        this.BringToFront();
        this.textBox1.Focus();
        this.textBox1.Text = string.Empty;
        System.Media.SystemSounds.Beep.Play();
    }
}

public void BringToBackAfterEnterCaptha()
{
    if (InvokeRequired)
    {
        Invoke(new Action(BringToBackAfterEnterCaptha));
    }
    else
    {
        this.TopMost = false;
    }
}

And I call them from background worker.

BringToFrontToEnterCaptha();
while (!ready)
{
    Thread.Sleep(100);
}
BringToBackAfterEnterCaptha();
Thread.Sleep(300);

And after pressing "Accept" button bool ready is set to true.

I works great but not always.

Mo Patel
  • 2,321
  • 4
  • 22
  • 37
Hooch
  • 28,817
  • 29
  • 102
  • 161
  • Does your app have input focus when it decides that it needs attention? – David Heffernan Mar 12 '11 at 13:47
  • What about input focus? You can't easily put your app on front without it. – David Heffernan Mar 12 '11 at 14:45
  • I am adding this as a comment as suggested: I dread the day your "personal" program escapes into the world and forces itself onto some unsuspecting user. If you need this, perhaps your design needs reviewing... – Vincent Vancalbergh Jan 02 '14 at 18:21
  • 1
    @VincentVancalbergh That was "private" program. But there no sense in that program if id didn't pop up for user. That whole idea of it. And it worked great. Now it is no longer used. – Hooch Jan 03 '14 at 14:31
  • funny, I was searching for a generic solution to bring a window to front and finding this answer which seems to do it for the same reason as mine - ocasional captcha passing :) – Alex P. Oct 02 '19 at 12:57

7 Answers7

212

Here is a piece of code that worked for me

this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;

It always brings the desired window to the front of all the others.

Mo Patel
  • 2,321
  • 4
  • 22
  • 37
Shabbir Hussain
  • 2,600
  • 2
  • 17
  • 25
  • 14
    of all the methods I've found using Google, and everyone's constant insistence that activation and focus where the key. This was the only approach that worked for me. Thank you, as I would never of thought of this trick. – Reactgular Sep 20 '12 at 18:48
  • 2
    Thanks. Out of all the solutions I've found on so far, this is the only one that seems to work all of the times. +1 – Alex Aug 12 '13 at 09:54
  • Works great for WPF application (opposite to Activate() method) – Illidan Sep 02 '13 at 12:09
  • 2
    Brilliant! Was the only thing that worked for me. Works for WinForm. Fortunately I could minimize and restore my app, since it didn't have any visible UI. This was also useful in another situation though: http://stackoverflow.com/questions/257587/bring-a-window-to-the-front-in-wpf/4831839#4831839 – gsb Oct 14 '13 at 11:13
  • 1
    Thanks - calling the Hide() method of my splash screen (in the Form::Load event) left my GUI in the background and only this (or calling Form.Activate() as per as-cii's answer) method seemed to work to bring it back! – Jon Cage Sep 12 '14 at 09:48
  • The only problem with this approach (which works very nicely as requested by the OP) is that it removes focus from the current window. So an app that's just supposed to stay in front while you work on something else would be interrupted by this. – Taylor Lopez Oct 23 '15 at 18:12
  • Thank you this works for me but I have one question, why does the code only work when windowstate is changed to normal after this.show() is called? – regularjoe Nov 23 '15 at 06:45
  • 1
    This has the unfortunate side effect of the window animating from a minimized state to normal state. For the app I'm working on, this was not acceptable. – Chad Oct 04 '17 at 15:25
  • 4
    `Activate()` solution is better. Also in your case it is good to check for and remember `Maximized` state. Otherwise when maximized you will restore it to `Normal`. – i486 Jul 31 '18 at 12:48
  • This is not working on Windows 10. It shows in the original Z order of all applications, so others could still stay in front. – ZZZ May 14 '19 at 01:42
  • worked like a champ in windows 10. – Steven Marcus Jul 19 '19 at 22:01
  • 1
    In my tests, `this.Show();` is not necessary. The form pops up regardless. – The Berga Nov 20 '19 at 10:19
  • This doesn't work if minimize box is disabled. – Gentleman Feb 17 '21 at 10:04
  • If even this fails, then there is an other **sweet dirty trick** with only 2 lines of code. Install nuget package **AutoItX.Dotnet**, which offers functionality of the AutoIt script language. .......... Simply add namespace `using AutoIt;` and then use this method with your window title: `AutoItX.WinActivate("MyWindowTitle");` .......... If needed, you can adjust the AutoIt settings to find the window by a substring of the title. ..... Worked fine for me, because in MVVM I had no access to the window object and `Application.Current.MainWindow` was not available. – Beauty Oct 22 '21 at 11:54
  • This was the only working solution for Forms that only display a TaskDialog. Using this code brought the TaskDialog to the front. Thank you! – soulflyman Feb 25 '22 at 16:25
98

Use Form.Activate() or Form.Focus() methods.

as-cii
  • 12,819
  • 4
  • 41
  • 43
  • I does Focus() in my Form1_Load function, but it doesn work (using Windows 8.1) – Simon Apr 25 '14 at 07:22
  • 22
    Form.Activate() works on it's own - thanks! – Jon Cage Sep 12 '14 at 09:51
  • 2
    "Activate" does make Windows bringing current form to front of any other application currently open within the O/S. On the other hand, "bring to front" only make desired form showing in front of other forms within current application (not O/S). – Simon Dugré Jan 18 '19 at 14:36
  • Form.Focus() did not work in my situation. .Activate() worked perfectly. The solution higher up in this thread to use .Minimized and .Normal worked properly but with an undesirable min/restore animation, so .Activate() was really the proper solution here for me. – blitz_jones May 28 '21 at 20:55
  • This should be accepted answer. `Form.Activate()` is a way to go – Mike Keskinov Nov 30 '21 at 05:25
64

While I agree with everyone, this is no-nice behavior, here is code:

[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);   


SetForegroundWindow(Handle.ToInt32());

Update

David is completely right, for completeness I include the list of conditions that must apply for this to work (+1 for David!):

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.
bluish
  • 26,356
  • 27
  • 122
  • 180
Dennis Smit
  • 1,168
  • 8
  • 12
  • 4
    Take a read of the bullet point list of [conditions](http://msdn.microsoft.com/en-us/library/ms633539(VS.85).aspx) that must apply for this to work. – David Heffernan Mar 12 '11 at 15:10
  • 13
    Form.Activate() calls SetForegroundWindow() avoiding the need for to use PInvoke. – Tony Edgecombe Jun 12 '12 at 14:58
  • It works like a charm with my splash screen, thx :) – Jerzy Gebler Feb 12 '15 at 11:20
  • This is the only solution that works for me. My bug for a reason that I don't know is Visual Studio that not automatically switch focus to the application after I run the project. Normally, with all my other applications, the switch is automatic but for one of them, I have to use this hack at the beginning for the program only in debug mode. – Samuel Sep 14 '16 at 18:10
  • Tried every offered solution here and this is the only one that worked but Dennis' bullet points (from Microsoft) above didn't exactly line up. I was already using SetForeGroundWindow() to bring a different app to the front then wanted to pop up a dialogue to enter some info pertaining to that application. I tried all the .Net solutions offered here (and half a dozen of my own dead ends) before seeing this point and thinking "Duh of course.". The fact that I'm running with Admin privileges is likely the reason it works even though I violate "there is no foreground process" bullet point. – shooky Sep 28 '19 at 13:09
  • This is the only solution that worked for me as well. I had a wait dialog box on another thread, and when I close it I wanted to shift focus back to main dialog, and this was the only answer that did that. – user890332 Nov 19 '19 at 16:18
45

Use Control.BringToFront:

myForm.BringToFront();
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 6
    Does this work if the app does not have input focus? – David Heffernan Mar 12 '11 at 13:50
  • 21
    This didn't work for me. – Jon Cage Sep 12 '14 at 09:50
  • 1
    @JonCage try `Application.OpenForms["yourForm"].BringToFront();` – FireFalcon Jun 12 '15 at 09:18
  • 29
    This is just wrong. Control.BringToFront will bring a control to the front of the hosting control, for example you might bring a TextBox in front of a Label to make sure that the label's whitespace does not obscure part of the TextBox. Form has inherited this from Control, and it can be used to change the z-order of the Form when it is an MDI child - i.e. the Form is hosted in another Form. It will not bring a form in front of another application. – jo0ls Nov 05 '15 at 10:22
  • 10
    Form.Activate() works, upvote answer below. – Sire Dec 24 '17 at 23:12
  • Works for me (at least for now) – Kai Wang Nov 18 '22 at 17:17
33

this works:

if (WindowState == FormWindowState.Minimized)
    WindowState = FormWindowState.Normal;
else
{
    TopMost = true;
    Focus();
    BringToFront();
    TopMost = false;
}
lupok
  • 1,025
  • 11
  • 15
  • Of all suggestions here, this is the only one that worked for me. :) – MojoDK Aug 30 '13 at 08:56
  • Forms.Activate() works end this solution no? very strange! Are you sure? – lupok Sep 12 '14 at 12:57
  • Yes, very sure. I've tried reducing my application down to something I could post here, but it doesn't replicate the problem in the first place. I must be doing something or setting something oddly somewhere that's causing your suggestion to fail :-/ – Jon Cage Sep 12 '14 at 14:40
  • Instead of `TopMost` "hack" you need 2 lines: `Activate(); BringToFront();`. Not sure which one is better to be first. – i486 Oct 17 '22 at 13:34
22

Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:

this.TopMost = true;
this.TopMost = false;

I have this code in my form's constructor, eg:

public MyForm()
{
    //...

    // Brint-to-front hack
    this.TopMost = true;
    this.TopMost = false;

    //...
}
Blaker
  • 769
  • 1
  • 8
  • 12
  • 1
    Under rare conditions this can cause a BSOD, ie with programs that change topmost for other windows, like a virtual/multiple desktop app. – Raphael Smit Jan 07 '16 at 17:16
  • Nop. http://stackoverflow.com/questions/17964598/can-a-user-mode-fault-cause-blue-screen-of-dead – lerthe61 Dec 14 '16 at 14:44
  • This should be the answer. – Bobby Turkalino Nov 01 '17 at 16:12
  • This is the only solution that I could get to bring it to the front without making it the active window. All the other solutions made the launching window lose focus. In my case I wanted the new window to show up on top without stealing focus, but after that the new window should act like a normal window regarding focus. – Bryce Wagner Oct 10 '18 at 22:33
  • Not worked first , But then I used a `System.Threading.Thread.Sleep(100);` after `this.TopMost = true;` and Boom , It works now ! Thanks. –  May 06 '19 at 21:20
  • Toggling `this.TopMost` adds a tiny bit of lag. It's imperceptible unless you are calling this repeatedly such as inside a `Resize` event handler (don't ask why I'm doing that.) – Walter Stabosz Jan 07 '22 at 20:00
  • This works. There always will be deviations from the "normal" or "expected" behavior and so you may encounter situation when this will not work, I have been using this for quite a while and rarely had to tweak it. VS2022 / .NET6 – Pepik Mar 19 '23 at 23:48
9

I use SwitchToThisWindow to bring the application to the forefront as in this example:

static class Program
{
    [DllImport("User32.dll", SetLastError = true)]
    static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);



    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool createdNew;
        int iP;
        Process currentProcess = Process.GetCurrentProcess();
        Mutex m = new Mutex(true, "XYZ", out createdNew);
        if (!createdNew)
        {
            // app is already running...
            Process[] proc = Process.GetProcessesByName("XYZ");

            // switch to other process
            for (iP = 0; iP < proc.Length; iP++)
            {
                if (proc[iP].Id != currentProcess.Id)
                    SwitchToThisWindow(proc[0].MainWindowHandle, true);
            }

            return;
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new form());
        GC.KeepAlive(m);

    }
Jim Lahman
  • 2,691
  • 2
  • 25
  • 21