C# 鼠标捕捉失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/437639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:22:51  来源:igfitidea点击:

Mouse capture is failing?

c#wpf

提问by Paul Williams

I want to be able to access the coordinates of the mouse whether or not the cursor is over the window of my application.

无论光标是否在我的应用程序窗口上,我都希望能够访问鼠标的坐标。

When I use Mouse.Capture(IInputElement) or UIElement.CaptureMouse(), both fail to capture the mouse and return false.

当我使用 Mouse.Capture(IInputElement) 或 UIElement.CaptureMouse() 时,都无法捕获鼠标并返回 false。

What might be my problem?

我的问题可能是什么?

The cs file for my window is as follows:

我的窗口的 cs 文件如下:

using System.Windows;
using System.Windows.Input;

namespace ScreenLooker
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            bool bSuccess = Mouse.Capture(this);
            bSuccess = this.CaptureMouse();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            tbCoordX.Text = e.GetPosition(this).X.ToString();
            tbCoordY.Text = e.GetPosition(this).Y.ToString();
            //System.Drawing.Point oPoint = System.Windows.Forms.Cursor.Position;
            //tbCoordX.Text = oPoint.X.ToString();
            //tbCoordY.Text = oPoint.Y.ToString();

            base.OnMouseMove(e);
        }
    }
}

采纳答案by Rhys

The control passed to Mouse.Capture()needs to be Visibleand Enabled.

传递给的控件Mouse.Capture()需要为VisibleEnabled

Try putting the Mouse.Capture in the Loadedevent handler, e.g.

尝试将 Mouse.Capture 放在Loaded事件处理程序中,例如

In XAML:

在 XAML 中:

<Window ... .. .. Title="My Window" loaded="Window_Loaded">
...
</Window>

In Code:

在代码中:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  var b = Mouse.Capture(this);
}

I've not captured the whole window before, so not sure about how it will work. The typical usage of it is.

我以前没有捕获整个窗口,所以不确定它是如何工作的。它的典型用法是。

  1. MouseDown:- call Mouse.Capture()on child control
  2. MouseMove:- Process X and Y coords of mouse
  3. MouseUp:- call Mouse.Capture(null)to clear mouse event capture.
  1. MouseDown:- 调用Mouse.Capture()子控件
  2. MouseMove:- 处理鼠标的 X 和 Y 坐标
  3. MouseUp:- 调用Mouse.Capture(null)清除鼠标事件捕获。