How to use a window hook to simulate a keystroke

I believe that what I'm trying to do is pretty simple, but it has been stuck for several hours. I have a window shape with a button. When I click the button, I want to execute the right mouse button with the coordinate 50, 50. This is outside the form, so I think it needs to be done using the window. Please, help.

+3
source share
1 answer

You should not use hook, but WinApi. You need one of two methods from USER32.DLL (read about the different ones on MSDN):

[DllImport("user32.dll")]
private static extern bool SendMessage(int hnd, Messages msg, int wParam, uint lParam);
[DllImport("user32.dll")]
private static extern bool PostMessage(int hWnd, Messages msg, int wParam, int lParam);

Messages is an enumeration, here it is:

enum Messages
{
     WM_LBUTTONDOWN = 0x201,
     WM_LBUTTONUP = 0x202,
     WM_RBUTTONDOWN = 0x204,
     WM_RBUTTONUP = 0x205
}

And with these methods, you must send special hWND messages equal to 0, which means sending messages to the desktop.

Here are the methods to help you:

public static void MouseLeftClick(Point p)
{
     int coordinates = p.X | (p.Y << 16);
     PostMessage(0, Messages.WM_LBUTTONDOWN, 0x1, coordinates);
     PostMessage(0, Messages.WM_LBUTTONUP, 0x1, coordinates);
}

public static void MouseRightClick(Point p)
{
     int coordinates = p.X | (p.Y << 16);
     PostMessage(0, Messages.WM_RBUTTONDOWN, 0x1, coordinates);
     PostMessage(0, Messages.WM_RBUTTONUP, 0x1, coordinates);
}

0 , , .

+3

All Articles