2015-09-05 275 views
0

我是c#的初學者,需要一些幫助。加載窗體後,我想在單擊鼠標時在鼠標的窗體座標上顯示。點擊可以在表格之外進行。例如在瀏覽器中。有人可以幫我弄這個嗎。如何獲取鼠標點擊時的座標

回答

0

我覺得你不能輕易地在你的Form以外處理鼠標點擊。 裏面的表格使用MouseEventArgs它可以簡單地處理。

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

Mouse Events in Windows Forms瞭解關於此主題的更多信息。

我希望它有幫助。

0

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

1

也許最簡單的方式是一種形式的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

儘管我的答案不僅有一種方法,但它也是一個很好和簡單的答案。 –