How can I bring my application window to the front?

C#.NetWinforms

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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

Solution 3 - C#

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.

Solution 4 - C#

Use Control.BringToFront:

myForm.BringToFront();

Solution 5 - C#

this works:

if (WindowState == FormWindowState.Minimized)
    WindowState = FormWindowState.Normal;
else
{
    TopMost = true;
    Focus();
    BringToFront();
    TopMost = false;
}

Solution 6 - C#

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;
    
    //...
}

Solution 7 - C#

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);

    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHoochView Question on Stackoverflow
Solution 1 - C#Shabbir HussainView Answer on Stackoverflow
Solution 2 - C#as-ciiView Answer on Stackoverflow
Solution 3 - C#Dennis SmitView Answer on Stackoverflow
Solution 4 - C#JonView Answer on Stackoverflow
Solution 5 - C#lupokView Answer on Stackoverflow
Solution 6 - C#BlakerView Answer on Stackoverflow
Solution 7 - C#Jim LahmanView Answer on Stackoverflow