如何捕获在(WPF)窗口之外发生的鼠标事件? [英] How can I capture mouse events that occur outside of a (WPF) window?

查看:1022
本文介绍了如何捕获在(WPF)窗口之外发生的鼠标事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Window元素,该元素具有WindowStyle="None"AllowsTransparency="True",因此它没有标题栏,并且支持透明度.

I have a Window element that has WindowStyle="None" and AllowsTransparency="True", therefore it has no title bar and supports transparency.

我希望用户能够通过在窗口内的任意位置上单击鼠标左键并拖动来将窗口移动到屏幕上的任何位置.只要按下鼠标左键,窗口就应随鼠标一起拖动.

I want the user to be able to move the Window to any position on the screen by left-clicking anywhere within the Window and dragging. The Window should drag along with the mouse as long as the left mouse button is pressed down.

我能够使用此功能,但有一个例外:当鼠标移到窗口的外部时(例如,在窗口边缘附近按下鼠标左键并快速移动鼠标时),窗口不再捕获鼠标位置,并且不会随鼠标一起拖动.

I was able to get this functionality to work with one exception: when the mouse moves outside of the Window (such as when the left mouse button was pressed down near the edge of the Window and the mouse is moved quicly), the Window no longer captures the mouse position and does not drag along with the mouse.

这是我用来完成工作的代码背后的代码:

Here is the code from the code-behind that I use to get the job done:

public Point MouseDownPosition { get; set; }
public Point MousePosition { get; set; }
public bool MouseIsDown { get; set; }

private void window_MyWindowName_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    MouseDownPosition = e.GetPosition(null);
    MouseIsDown = true;
}

private void window_MyWindowName_MouseMove(object sender, MouseEventArgs e)
{
    if (MouseIsDown)
    {
        MousePosition = e.GetPosition(null);
        Left += MousePosition.X - MouseDownPosition.X;
        Top += MousePosition.Y - MouseDownPosition.Y;
    }
}

private void window_MyWindowName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    MouseIsDown = false;
}

推荐答案

我相信您正在重新发明轮子.搜索"Window.DragMove".

I believe you are reinventing the wheel. Search for "Window.DragMove".

示例:

    private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        this.DragMove();
    }

这篇关于如何捕获在(WPF)窗口之外发生的鼠标事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆