4

I know how to modify cursor position from examples on MSDN.

My question is how to check position of mouse while mouse moves and then print X and Y position to representing labels?

EDIT: Lets say I want to track my mouse position from my entire screen.

EDIT 2: My app will be in the back ground/minimized.

I'm already using Mouse Hooks:

namespace Program
{
    public partial class MouseHook
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);

        private const int MOUSEEVENTF_LEFTDOWN = 0x02;
        private const int MOUSEEVENTF_LEFTUP = 0x04;
        private const int MOUSEEVENTF_RIGHTDOWN = 0x08;
        private const int MOUSEEVENTF_RIGHTUP = 0x10;

        public void DoMouseClick()
        {
            int X = Cursor.Position.X;
            int Y = Cursor.Position.Y;

            IntPtr newP = new IntPtr(Convert.ToInt64("0", 16));
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, newP);
        }
    }
}
N_A
  • 19,799
  • 4
  • 52
  • 98
HelpNeeder
  • 6,383
  • 24
  • 91
  • 155
  • 4
    This has been asked many times already. Type "+setwindowshookex +wh_mouse_ll" in the search box. Or just use a 50 msec Timer and Cursor.Position – Hans Passant Jan 15 '12 at 17:38
  • @Hans Passant, Timer solution seems to be the simplest for checking the x/y position. I just need to figure out how to check the position now. +1 for this :) – HelpNeeder Jan 15 '12 at 17:41
  • @Cody Gray, how is this question a duplicate if question was posted 3 years before noted answer? – HelpNeeder Apr 30 '17 at 18:32

3 Answers3

3

Here is the msdn documentation on system level mouse event handling calls (low level mouse proc).

Here is an example of using low level mouse procs to change the scroll event.

In the answer in the second link use WM_MOUSEMOVE from here instead of WM_MOUSEWHEEL.

One thing to note: for this program to continue to capture mouse events when the mouse is over a program with elevated privileges, this program will have to be launch with elevated privileges.

Code (not tested):

using System;

using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace CatchMouseMove
{
    class InterceptMouse
    {
        const int INPUT_MOUSE = 0;
        const int MOUSEEVENTF_WHEEL = 0x0800;
        const int WH_MOUSE_LL = 14; 


        private static LowLevelMouseProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;

        public static void Main()
        {
            _hookID = SetHook(_proc);

            if (_hookID == null)
            {
                MessageBox.Show("SetWindowsHookEx Failed");
                return;
            }
            Application.Run();
            UnhookWindowsHookEx(_hookID);
        }

        private static IntPtr SetHook(LowLevelMouseProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_MOUSE_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            int xPos = 0;
            int yPos = 0;

            if (nCode >= 0 && MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam)
            {    
                xPos = GET_X_LPARAM(lParam); 
                yPos = GET_Y_LPARAM(lParam);

                //do stuff with xPos and yPos
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }


        private enum MouseMessages
        {
            WM_MOUSEMOVE = 0x0200
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            public int x;
            public int y;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct MSLLHOOKSTRUCT
        {
            public POINT pt;
            public int mouseData;
            public int flags;
            public int time;
            public IntPtr dwExtraInfo;
        }

        public struct INPUT
        {
            public int type;
            public MOUSEINPUT mi;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MOUSEINPUT
        {
            public int dx;
            public int dy;
            public int mouseData;
            public uint dwFlags;
            public int time;
            public int dwExtraInfo;
        }



        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

    }

}
Community
  • 1
  • 1
N_A
  • 19,799
  • 4
  • 52
  • 98
3

You need to set a Windows hook in order to achieve this. The MSDN article How to set a Windows hook in Visual C# .NET shows how to set a mouse hook.

I tried it, it captures the mouse all over the form, even when the mouse cursor is over a control.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
2

You can use the EventArgs of the MouseMove event, because it holds the mouse coordinates. From there you can easily set the text property of the label to the X or Y coordinate you will take from e (the MouseMove EventArgs).

private void Form_MouseMove(object sender, MouseEventArgs e)
{
    // Update the mouse coordinates displayed in the textbox.
    myTextBox.Text = e.Location.ToString();
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
matteeyah
  • 855
  • 11
  • 24
  • Ok, I get the idea. But since I must have an object to do the handler to for example: `textBox1.TextChanged += new EventArgs(textBox1_TextChanged);` which object would I call? – HelpNeeder Jan 15 '12 at 16:53
  • 1
    @Help: `TextChanged` is the wrong event. You want to handle the `MouseMove` event. Inside of that event handler method, update your textbox: `textBox1.Text = e.Location.ToString();` – Cody Gray - on strike Jan 15 '12 at 16:56
  • @Cody Gray, I do know. But my question is what object I would refer to, meaning what I would substitute textBox1 to? – HelpNeeder Jan 15 '12 at 16:58
  • @Help: Oh, probably your Form. The problem you'll run into is that whenever the cursor moves over a child control that is on top of the form, it won't raise the event on the form. – Cody Gray - on strike Jan 15 '12 at 17:00
  • 1
    Do you really need to track mouse movements in the entire window, or just some control (like a pane, etc.)? – Vladislav Zorov Jan 15 '12 at 17:02
  • @Vladislav Zorov, I would prefer to track mouse over my entire screen. – HelpNeeder Jan 15 '12 at 17:12
  • Oh... that changes a lot.. I guess there should be some Windows API, but it gets more complicated. Games do it by opening a window exactly as big as the screen, which contains a single pane that receives events and gets drawn to. – Vladislav Zorov Jan 15 '12 at 17:17
  • @Vladislav Zorov, I'm sorry. I have updated my OP. Also I want to point out that I want my app to track the cursor while being in background. – HelpNeeder Jan 15 '12 at 17:20