How to disable a dialog from hiding

If I create a class derived from System.Windows.Window and show it using ShowDialog, it will appear above the main window, as expected, and the main window is disabled. However, you can place both windows behind other applications, and then simply return the main window. It just leaves one window that seems to have broken and can be confusing.

Is it possible to guarantee that a dialog is always displayed if the main window is displayed? The MessageBox.Show dialog box does not have such problems.

Update:

The test dialog is defined as

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

and called using

  MyDialog d = new MyDialog(); d.ShowDialog(); 
+8
c # wpf modal-dialog
source share
3 answers

you need to set the Owner property.

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

To make sure that the dialog is always displayed if the main window is displayed, add a handler to the main form visibility change event to set TopMost true or false to the child form according to the 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 of is to use a timer with the user32 dll getforegroundwindow to check if the main form is visible.

+1
source share

This code should work the way 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; 
+1
source share

All Articles