Zolomon
Zolomon

Reputation: 9785

C#: How do I get the coordinates of my mouse when left/right mouse button has been pressed?

How do I get the coordinates of my mouse when left/right mouse button has been pressed?

I am using a low level mouse hook and am able to get the current position of my cursor, but I would like to be able to retrieve the position when any mouse button has been pressed.

How can I do this?

Upvotes: 3

Views: 2253

Answers (6)

Zolomon
Zolomon

Reputation: 9785

http://www.codeproject.com/KB/vb-interop/MouseHunter.aspx - I found this little charming piece of information. Sadly Visual Studio 2008 won't accept the dll that's been precompiled, and I can't get Visual Basic 6 to install on my machine to try to recompile it.

Upvotes: 0

Zolomon
Zolomon

Reputation: 9785

http://www.codeproject.com/KB/system/globalsystemhook.aspx - this solved my problem. Used the DLL's from the demo project and managed to get the coordinates.

Upvotes: 0

Graviton
Graviton

Reputation: 83244

Why don't you just capture the MouseDown Event, and from the MouseEventArgs, obtain the position of the click by using MouseEventArgs.Location?

Upvotes: 3

user113476
user113476

Reputation:

The wParam argument of your MouseHook procedure will contain the message identifier WM_LBUTTONDOWN, WM_LBUTTONUP, WM_RBUTTONDOWN, WM_RBUTTONUP, etc.. from this you can determine what the button state is at the current coordinates.

Upvotes: 0

Mitch Wheat
Mitch Wheat

Reputation: 300489

In your MouseHook method:

public static int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
    //Marshall the data from the callback.
    MouseHookStruct MyMouseHookStruct = 
         (MouseHookStruct) Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

    if (nCode >= 0)
    {
        int xcoord = MyMouseHookStruct.pt.x;
        int ycoord = MyMouseHookStruct.pt.y;
    }

    return CallNextHookEx(hHook, nCode, wParam, lParam); 
}

From here.

Upvotes: 0

John Knoeller
John Knoeller

Reputation: 34128

call GetMessagePos() on WM_LBUTTONDOWN to get what you want. But I doubt that it will work inside a low-level mousehook. It's meant to be used in your message pump or window proc.

"The GetMessagePos function retrieves the cursor position for the last message retrieved by the GetMessage function."

Are you sure you need a hook?

Upvotes: 0

Related Questions