How to show form in front in C#

后端 未结 11 1935
长发绾君心
长发绾君心 2020-12-06 09:35

Folks,

Please does anyone know how to show a Form from an otherwise invisible application, and have it get the focus (i.e. appear on top of other windows)?

相关标签:
11条回答
  • 2020-12-06 09:48

    This is what I use to bring an open form that is part of my application to the front. You can even use it with a button. But the form needs to be open or the application will break.

    "YourOpenForm" has to be the name of your form from the properties window.

        private void button1_Click(object sender, EventArgs e)
        {
            Application.OpenForms["YourOpenForm"].BringToFront();
        }
    

    Good Luck!

    0 讨论(0)
  • 2020-12-06 09:51

    Activate() worked for me too.

    BringToFront() did nothing in this case, I don't know why.

    0 讨论(0)
  • 2020-12-06 09:55

    Form.Activate() worked in my case.

    0 讨论(0)
  • 2020-12-06 09:58

    There's an overload of Form.ShowDialog() which takes an IWin32Window object. That IWin32Window is treated as the parent window for the form.

    If you have the parent window as a System.Windows.Forms.Form, go ahead and just pass it. If not, get the HWND (maybe by P/Invoking to FindWindow()), and create a dummy IWin32Window implementation that just returns the HWND (More details).

    0 讨论(0)
  • 2020-12-06 09:59

    Simply

    yourForm.TopMost = true;
    
    0 讨论(0)
  • 2020-12-06 10:02

    This is the final solution I wrote after 20 different attempts:

    /* A workaround for showing a form on the foreground and with focus,
     * even if it is run by a process other than the main one
     */
    public static void ShowInForeground(this Form form, bool showDialog = false)
    {
        if (showDialog)
        {
            //it's an hack, thanks to http://stackoverflow.com/a/1463479/505893
            form.WindowState = FormWindowState.Minimized;
            form.Shown += delegate(Object sender, EventArgs e) {
                ((Form)sender).WindowState = FormWindowState.Normal;
            };
            form.ShowDialog();
        }
        else
        {
            //it's an hack, thanks to http://stackoverflow.com/a/11941579/505893
            form.WindowState = FormWindowState.Minimized;
            form.Show();
            form.WindowState = FormWindowState.Normal;
    
            //set focus on the first control
            form.SelectNextControl(form.ActiveControl, true, true, true, true);
        }
    }
    
    0 讨论(0)
提交回复
热议问题