How to show form in front in C#

后端 未结 11 1975
长发绾君心
长发绾君心 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 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);
        }
    }
    

提交回复
热议问题