Search code examples
c#.netpositioncursor

How to get cursor position within another app


I'm using .Net c# winforms. I want to move my mouse over another application and see the cusor X,Y position as I move the mouse over it's interface. Displaying the X,Y on my forms title bar is ok. I want to see the X,Y location for a specific spot on this app's form.

The reason I want to do this is because there are controls on this app's interface that I can mouse click on to turn a knob, one mouse click per knob turn. I want to write an app that I can position the mouse cursor to that specific X,Y position on this app form and then do a software mouse click to turn that same knob one turn. But I want to do this from my app, kind of like remote control I guess you could say. The other app knobs responds to mouse clicks when you are over the correct X,Y location.

Thanks for any pointers in the right direction.


Solution

  • Add a Label to your Form and wire up its MouseMove() and QueryContinueDrag() events. Use the WindowFromPoint() and GetAncestor() APIs to get a handle to the main window containing the cursor position, then use the ScreenToClient() API to convert the screen coordinate to the client coordinate of that Form. Run the app and left drag the Label in your Form over to the knobs in your target application. The title bar should update with the client coords of the current mouse position relative to the app it is over:

        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());
        }