Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 769
David Sykes Avatar asked May 31 '12 07:05

David Sykes


3 Answers

you have to set the Owner property.

MyDialog d = new MyDialog();
d.Owner = Application.Current.MainWindow;//or your owning window
d.ShowDialog();
like image 141
blindmeis Avatar answered Nov 04 '22 09:11

blindmeis


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.

like image 1
Amen Ayach Avatar answered Nov 04 '22 09:11

Amen Ayach


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;
like image 1
Klaus78 Avatar answered Nov 04 '22 09:11

Klaus78