Search code examples
c#wpfwindowswindowshowdialog

Is there an event or something i can use when a showdialogwindow is blocking the window i try to access


I have 2 windows. Lets call them A and B. A is opening B with a ShowDialog(). So I am opening B - When the user minimizes B or gets it into the back somehow and he tries clicking window A again its blocked (as it should be), but is there an Event that I can catch up onto when this happens ?

I am trying to achieve bringing the blocking window B into the front when hes trying to access window A with window B opened.

Codeexample:

Thats how Window A is opened from the Mainwindow

            WindowA windowA = new WindowA();

            windowA.Owner = Application.Current.MainWindow;

            windowA.Show();
            windowA.Activate();

And thats how Window B is opened

            WindowB windowB = new WindowB();
            windowB.Owner = this; //(this = windowA)
            windowB.ShowDialog();

Both windows have no special properties set except

WindowStartupLocation="CenterScreen"

Solution

  • If you want to restore second window when it is minimized and user does click on first(blocked) window, then you can go this way(add this code to the WindowB):

    public WindowB()
    {
        PreviewMouseDown += WindowB_PreviewMouseDown;
        StateChanged += WindowB_StateChanged;
        InitializeComponent();
        LostMouseCapture += WindowB_LostMouseCapture;
    
    }
    
    private void WindowB_LostMouseCapture(object sender, MouseEventArgs e)
    {
        //You can also evaluate here a mouse coordinates.
        if (WindowState == WindowState.Minimized)
        {
            e.Handled = true;
            CaptureMouse();
        }
    }
    
    private void WindowB_StateChanged(object sender, EventArgs e)
    {
        if (WindowState== WindowState.Minimized)
        {
            CaptureMouse();
        }
        else
        {
            ReleaseMouseCapture();
        }
    }
    
    private void WindowB_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        WindowState = WindowState.Normal;
        Debug.WriteLine("WindowB PreviewMouseDown");
    }
    

    So you have to start mouse capturing on second window on it being minimized, for if user does click on WindowA this can be handled on WindowB.
    As window being minimized it going to lost a mouse capture(therefore you have to listen on LostMouseCapture), that you have to prevent.

    Left mouse button down on WindowA does restore thenWindowB.