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
Mouse capture is failing?
提问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()
需要为Visible和Enabled。
Try putting the Mouse.Capture in the Loaded
event 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.
我以前没有捕获整个窗口,所以不确定它是如何工作的。它的典型用法是。
- 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.
- MouseDown:- 调用
Mouse.Capture()
子控件 - MouseMove:- 处理鼠标的 X 和 Y 坐标
- MouseUp:- 调用
Mouse.Capture(null)
清除鼠标事件捕获。