[c#] How can I bring my application window to the front?

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.

This question is related to c# .net winforms

The answer is


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.


this works:

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

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


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

    }

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;

    //...
}

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.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager