WPF intercept clicks outside a modal window

别来无恙 提交于 2019-12-02 11:47:53

问题


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 will not be shown on top of the active window, and, for now, this is the only way to display it correctly. I haven't found a proper way to do just that (since the "deactivate" event will no longer be triggered..)


回答1:


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.




回答2:


Well one way is to hook up the event handler on your main app and respond to it when you have that window open:

EventManager.RegisterClassHandler(typeof(Window), Mouse.MouseDownEvent, new MouseButtonEventHandler(OnMousepDown), true);

or

  EventManager.RegisterClassHandler(typeof(yourAppClassName),   Mouse.PreviewMouseDownEvent, new MouseButtonEventHandler(OnMousepDown), true);

//this is just a sample..
private void OnMousepDown(object sender, MouseButtonEventArgs e)
    {
        if (thatWindowThatYourTalkingAbout.IsOpen) 
            ..do something 
    }


来源:https://stackoverflow.com/questions/10299856/wpf-intercept-clicks-outside-a-modal-window

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!