2015-09-27 13 views
0

我正在使用.Net c#winforms。我想將鼠標移到另一個應用程序上,並在將鼠標移到其界面上時查看X,Y位置的座標。在我的表格標題欄上顯示X,Y是可以的。我想看看這個應用程序表單上特定位置的X,Y位置。如何在另一個應用程序中獲取光標位置

我想這樣做的原因是因爲在這個應用程序的界面上有控件,我可以用鼠標點擊旋轉旋鈕,每旋鈕一次鼠標點擊一次。我想編寫一個應用程序,讓我可以將鼠標光標定位在此應用程序表單上特定的X,Y位置,然後單擊一次軟件鼠標即可旋轉同一個旋鈕。但我想從我的應用程序這樣做,有點像遙控器,我想你可以說。當您位於正確的X,Y位置時,其他應用程序旋鈕會響應鼠標點擊。

感謝您指出正確的方向。

回答

2

將標籤添加到您的窗體並連接其MouseMove()和QueryContinueDrag()事件。使用WindowFromPoint()和GetAncestor()API獲取包含光標位置的主窗口句柄,然後使用ScreenToClient()API將屏幕座標轉換爲該窗體的客戶端座標。運行應用程序並將標籤拖到您的目標應用程序中的旋鈕上。標題欄應相對於應用程序的當前鼠標位置的客戶COORDS更新結束後:

private const uint GA_ROOT = 2; 

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] 
    public struct POINT 
    { 
     public int X; 
     public int Y; 
    } 

    [System.Runtime.InteropServices.DllImport("user32.dll")] 
    private static extern IntPtr WindowFromPoint(int xPoint, int yPoint); 

    [System.Runtime.InteropServices.DllImport("user32.dll", ExactSpelling = true)] 
    private static extern IntPtr GetAncestor(IntPtr hwnd, uint gaFlags); 

    [System.Runtime.InteropServices.DllImport("user32.dll")] 
    private static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint); 

    private void label1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.Button == MouseButtons.Left) 
     { 
      label1.DoDragDrop(label1, DragDropEffects.Copy); 
     } 
    } 

    private void label1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) 
    { 
     Point pt = Cursor.Position; 
     IntPtr wnd = WindowFromPoint(pt.X, pt.Y); 
     IntPtr mainWnd = GetAncestor(wnd, GA_ROOT); 
     POINT PT; 
     PT.X = pt.X; 
     PT.Y = pt.Y; 
     ScreenToClient(mainWnd, ref PT); 
     this.Text = String.Format("({0}, {1})", PT.X.ToString(), PT.Y.ToString()); 
    } 
+0

這真是棒極了...!非常感謝...這比我想象的更復雜。我如何給你信貸? – user337447

+0

您應該使用MouseMove事件而不是Cursor.Position的座標。他們是與硬件事件相關的人。 –

+0

@用戶您提出了很多問題,從未接受過答案,也從未投過票。你能解決這個問題嗎? –

相關問題