鼠标捕获失败?
问题描述:
无论光标是否在应用程序窗口上方,我都希望能够访问鼠标的坐标。
I want to be able to access the coordinates of the mouse whether or not the cursor is over the window of my application.
当我使用Mouse.Capture( IInputElement)或UIElement.CaptureMouse()都无法捕获鼠标并返回false。
When I use Mouse.Capture(IInputElement) or UIElement.CaptureMouse(), both fail to capture the mouse and return false.
我的问题是什么?
我窗口的cs文件如下:
The cs file for my window is as follows:
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);
}
}
}
答
传递给 Mouse.Capture()
的控件需要可见和启用。
尝试将Mouse.Capture放入 Loaded
事件处理程序中,例如
Try putting the Mouse.Capture in the Loaded
event handler, e.g.
在XAML中:
<Window ... .. .. Title="My Window" loaded="Window_Loaded">
...
</Window>
在代码中:
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.
- MouseDown:-调用
Mouse.Capture()
在子控件上 - MouseMove:-处理鼠标的X和Y坐标
- MouseUp:-调用
Mouse.Capture( null)
清除鼠标事件捕获。
- MouseDown:- call
Mouse.Capture()
on child control - MouseMove:- Process X and Y coords of mouse
- MouseUp:- call
Mouse.Capture(null)
to clear mouse event capture.