WPF intercept clicks outside a modal window

后端 未结 2 612
日久生厌
日久生厌 2021-01-21 07:38

Is it possible to check when the user has clicked outside a modal window? I\'d like to somehow circumvent the modal logic because if the window isn\'t displayed as modal, it wil

2条回答
  •  北海茫月
    2021-01-21 08:21

    Even if it's a modal window (displayed with ShowDialog() calls), one can add some even handlers to the window's class and make it check for the mouse clicks outside the window like this:

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (posX < 0 || posX > this.Width || posY < 0 || posY > this.Height)
                this.Close();            
        }
    
        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            Point p = e.GetPosition(this);
    
            posX = p.X; // private double posX is a class member
            posY = p.Y; // private double posY is a class member
        }
    
        private void Window_Activated(object sender, EventArgs e)
        {
            System.Windows.Input.Mouse.Capture(this, System.Windows.Input.CaptureMode.SubTree);
        }
    

    This did the job for me, in a difficult context: mingled MFC, WindowsForms mammoth of an app - no interop, no other complicated stuff. Hope it helps others facing this odd behavior.

提交回复
热议问题