如何获取鼠标点击时的坐标

问题描述:

我是c#的初学者,需要一些帮助。加载窗体后,我想在单击鼠标时在鼠标的窗体坐标上显示。点击可以在表格之外进行。例如在浏览器中。有人可以帮我弄这个吗。如何获取鼠标点击时的坐标

我觉得你不能轻易地在你的Form以外处理鼠标点击。 里面的表格使用MouseEventArgs它可以简单地处理。

private void Form1_MouseClick(object sender, MouseEventArgs e) 
{ 
    // e.Location.X & e.Location.Y 
} 

Mouse Events in Windows Forms了解关于此主题的更多信息。

我希望它有帮助。

Cursor.PositionControl.MousePosition都返回鼠标光标在屏幕坐标中的位置。

以下文章处理捕获Global鼠标点击事件:

Processing Global Mouse and Keyboard Hooks in C#
Global Windows Hooks

+0

这是正确的,但如果他想处理click事件? (他说) –

+0

@MohammadChamanpara的P/Invoke https://msdn.microsoft.com/en-us/library/ms646262.aspx(SetCapture)。编辑:我已经添加链接到文章,处理'全球'输入事件。 – matteeyah

也许最简单的方式是一种形式的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

尽管我的答案不仅有一种方法,但它也是一个很好和简单的答案。 –

你需要一个全球性的鼠标钩子。

See this question