Reputation: 49812
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
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
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
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