wpf 如何获取Click Outside Window事件

u7up0aaq  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(141)

我做了一个简单的窗口:

var wndPpList = new Window()
{
    SizeToContent = SizeToContent.WidthAndHeight,
    WindowStyle = WindowStyle.None,
    ShowInTaskbar = false,
    BorderBrush = GetColour_Cyan(),
    BorderThickness = new Thickness(3),
};

现在我想做的是,当我在它外面点击时,它就关闭了。
我看过很多帖子,为了实现这一点,他们激活鼠标

wndPpList.CaptureMouse();
wndPpList.Deactivated += (sender, args) => 
{
    wndPpList.ReleaseMouseCapture();
    wndPpList.Close();
};

但事件Deactivated只是不被激发。
谢谢你的帮助
帕特里克

3npbholx

3npbholx1#

使用MouseDown事件,你可以检查事件是否在弹出窗口之外引发。然后你可以关闭弹出窗口。

public MainWindow()
        {
            InitializeComponent();

            var wndPpList = new Window()
            {
                SizeToContent = SizeToContent.WidthAndHeight,
                WindowStyle = WindowStyle.None,
                ShowInTaskbar = false,
                BorderBrush =  Brushes.Cyan,
                BorderThickness = new Thickness(3),
            };
            wndPpList.Show();

            // Handle the mouse down event of the application window
            Application.Current.MainWindow.MouseDown += (s, e) =>
            {
                if (!wndPpList.IsMouseOver)
                {
                    wndPpList.Close();
                }
            };
        }

如果你需要触发事件超过一次,你需要注册和注销它正确.这是一个按钮打开弹出窗口的例子.然而,如果你打开两个弹出窗口在同一时间,你会得到problems.所以你应该禁用按钮,而弹出显示或使用一些其他机制,只显示一个弹出窗口.

public partial class MainWindow : Window
    {
        private MouseButtonEventHandler windowMouseDownHandler;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            UnregisterMouseDownEvent();
            var wndPpList = new Window()
            {
                SizeToContent = SizeToContent.WidthAndHeight,
                WindowStyle = WindowStyle.None,
                ShowInTaskbar = false,
                BorderBrush = Brushes.Cyan,
                BorderThickness = new Thickness(3),
            };
            wndPpList.Show();

            windowMouseDownHandler = (s, e) =>
            {
                if (!wndPpList.IsMouseOver)
                {
                    wndPpList.Close();
                }
            };
            // Register the event handler function
            Application.Current.MainWindow.MouseDown += windowMouseDownHandler;
        }

        private void UnregisterMouseDownEvent()
        {
           
            if (windowMouseDownHandler != null)
            {
                Application.Current.MainWindow.MouseDown -= windowMouseDownHandler;
            }
           
        }

相关问题