Using SendMessage to simulate mouse clicks

Doon picture Doon · Feb 14, 2013 · Viewed 25.8k times · Source

What I need

Simulate messages (mouse mainly, but keyboard too) without moving the cursor. The message goes to the focused window (at first, I want for minimized windows, but I didn't find how to do it, so I use SetForegroundWindowto focus it).

What I've found

On this question, I've figured out I need to use pInvoked from user32.dll. Also I found a small code sample, but it didn't work.

I also found this similar question. The guy uses mouse_event, but it is deprecated. This function takes the X and Y cordinates in mickeys. I tried to convert my coordinates (using SendMessage), but I failed.

Icanhaz an example?

Sure. The notepad.exe is opened and I need to peform a right click on a button located at (1210, 460).

What I've tried

Based on the sample that I've found here, I did this code:

IntPtr hWnd = (IntPtr)FindWindow("notepad.exe", null);
SetForegroundWindow(hWnd);

var screenPoint = this.PointToScreen(new Point(1210, 460));
var handle = WindowFromPoint(screenPoint);

if (handle != IntPtr.Zero)
{
    //Right Button Down
    SendMessage(handle, 0x0204, IntPtr.Zero, IntPtr.Zero);
    //Right Button Up
    SendMessage(handle, 0x0205, IntPtr.Zero, IntPtr.Zero);
}

I also tried using my previous handle hWnd in SendMessage, but didn't work as well. The whole code you can find here.

Thank you in advance.

Answer

Abyte0 picture Abyte0 · Feb 25, 2013

If I corectly understand, you want to inject a click event inside an application without having to move the mouse, like a game bot, so the user don't see sumthing is using his mouse and keyboard...

If im right, then look at the reply at this link, it may be what you want...

its in c++ but well not a big matter I guess...

http://social.msdn.microsoft.com/Forums/en-SG/vcgeneral/thread/e0071733-286a-4b4d-b294-685f8a788fb8