如何获取鼠标点击时的坐标
答
我觉得你不能轻易地在你的Form
以外处理鼠标点击。 里面的表格使用MouseEventArgs
它可以简单地处理。
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
// e.Location.X & e.Location.Y
}
在Mouse Events in Windows Forms了解关于此主题的更多信息。
我希望它有帮助。
答
Cursor.Position
和Control.MousePosition
都返回鼠标光标在屏幕坐标中的位置。
以下文章处理捕获Global
鼠标点击事件:
Processing Global Mouse and Keyboard Hooks in C#
Global Windows Hooks
答
也许最简单的方式是一种形式的Capture
属性设置为true
,然后处理单击事件和转换位置(这是与形式的左上角相关的位置)使用PointToScreen
形式的方法来屏幕位置。
例如,你可以把一个按钮的形式和做:
private void button1_Click(object sender, EventArgs e)
{
//Key Point to handle mouse events outside the form
this.Capture = true;
}
private void MouseCaptureForm_MouseDown(object sender, MouseEventArgs e)
{
this.Activate();
MessageBox.Show(this.PointToScreen(new Point(e.X, e.Y)).ToString());
//Cursor.Position works too as RexGrammer stated in his answer
//MessageBox.Show(this.PointToScreen(Cursor.Position).ToString());
//if you want form continue getting capture, Set this.Capture = true again here
//this.Capture = true;
//but all clicks are handled by form now
//and even for closing application you should
//right click on task-bar icon and choose close.
}
但更正确的(略难)的方法是使用全局钩子。
如果你真的需要做到这一点,你可以在这个链接看看:
+0
尽管我的答案不仅有一种方法,但它也是一个很好和简单的答案。 –
这是正确的,但如果他想处理click事件? (他说) –
@MohammadChamanpara的P/Invoke https://msdn.microsoft.com/en-us/library/ms646262.aspx(SetCapture)。编辑:我已经添加链接到文章,处理'全球'输入事件。 – matteeyah