David Sykes
David Sykes

Reputation: 49812

How can I stop a dialog window from getting hidden

If I create a class derived from System.Windows.Window and show it with ShowDialog it appears above the main window as expected, and the main window is disabled. However it is possible to put both windows behind other applications, and then just bring the main window back. This just leaves a single window which appears to have crashed, and can be confusing.

Is it possible to ensure that the dialog window is always displayed if the main window is shown? The MessageBox.Show dialog has no such problems

Update:

A test dialog is defined as

public partial class MyDialog : Window
{
    public MyDialog()
    {
        InitializeComponent();
    }
}

and called using

    MyDialog d = new MyDialog();
    d.ShowDialog();

Upvotes: 9

Views: 4258

Answers (3)

Klaus78
Klaus78

Reputation: 11896

This code should work as you want

public MainWindow()
    {
        InitializeComponent();

        this.Activated += new EventHandler(MainWindow_Activated);
    }

    void MainWindow_Activated(object sender, EventArgs e)
    {
        if (m == null)
            return;

        m.Activate();
    }


    private void button1_Click(object sender, RoutedEventArgs e)
    {
        m = new MyDialog();
        m.ShowDialog();
    }
    MyDialog m;

Upvotes: 1

Amen Ayach
Amen Ayach

Reputation: 4348

To ensure that the dialog window is always displayed if the main window is shown, add handler to main form visibility changed event to set TopMost true or false to child form according to main visibility

ChildForm frmDLg = null;
public MainForm()
{
    this.VisibleChanged += MainFrmVisibleChanged;
}

private void LoadDialogForm()
{
    try {
        if (frmDLg == null || frmDLg.IsDisposed) {
            frmDLg = new ChildForm();
        }
        frmDLg.ShowDialog();
    } catch (Exception ex) {
        //Handle exception
    }
}

private void MainFrmVisibleChanged(object sender, System.EventArgs e)
{
    if (frmDLg != null && !frmDLg.IsDisposed) {
        frmDLg.TopMost = this.Visible;
    }
}

Update

public override bool Visible
        {
            get
            {
                return base.Text;
            }
            set
            {
                base.Text = value;
                // Insert my code
                if (frmDLg != null && !frmDLg.IsDisposed)
                {
                    frmDLg.TopMost = this.Visible;
                }
            }
        }

The last cure i can think is to use a timer with user32 dll getforegroundwindow to check if main form is visible.

Upvotes: 1

blindmeis
blindmeis

Reputation: 22435

you have to set the Owner property.

MyDialog d = new MyDialog();
d.Owner = Application.Current.MainWindow;//or your owning window
d.ShowDialog();

Upvotes: 8

Related Questions