views:

29

answers:

1

ShowDialog() doesn't bring form to top when the owner is minimized. It is shown and visible, but it is not focused and behind the current window. Even using the commented lines, I see the issue.

    public void Form1_Click(object sender, EventArgs e)
    {
        this.WindowState = FormWindowState.Minimized;
        // this.Hide();
        using (var f = new Form1())
        {
            // this.WindowState = FormWindowState.Normal;
            f.Text = "ShowDialog()";
            f.Click -= new EventHandler(f.Form1_Click);
            f.ShowDialog(this); // f is not on top?
            this.Show();
        }
    }
+1  A: 
    this.WindowState = FormWindowState.Minimized;

As soon as that executes, there is no window left in your application that can still receive the focus. Windows needs to find another one to give the focus to, it will be a window of another app. A bit later your dialog shows up, but that's too late, focus is already lost.

Using a trick like Control.BeginInvoke() to minimize the form after the dialog is displayed doesn't work either, the dialog automatically closes when it parent minimizes. The best you can do is hide it. You'll have to use the same trick to restore it before the dialog closes or you'll still lose focus. Like this:

    protected override void OnClick(EventArgs e) {
        using (var f = new Form1()) {
            f.Text = "ShowDialog()";
            this.BeginInvoke(new Action(() => this.Hide()));
            f.FormClosing += delegate { this.Show(); };
            f.ShowDialog();
        }
    }
Hans Passant
Thanks for the response; but in the real version of this the main form has been minimized and hidden for who knows how long before the user tries to show the dialog form with a HotKey. Also the dialog isn't closed, it is simply behind the top window.
CrashCodes