06 October 2014

.net - Discretely perform a mouse click

For an application I needed to perform a mouse click on a control in a way the user wouldn't even notice it. This was achieved as follows:

First the following Windows functions need to be imported. I've put these in a static class called "OS".

[StructLayout(LayoutKind.Sequential)]
public struct Win32Point {
  public Int32 X;
  public Int32 Y;
};

[DllImport("user32.dll")]
public static extern bool GetCursorPos(ref Win32Point pt);

[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);

The control in question is hidden. On it's load event this takes place:

OS.Win32Point pos = new OS.Win32Point();
OS.GetCursorPos(ref pos); //Gets the current mouse position.

int x = ((int)Left + (int)Width) - 220;
int y = ((int)Top + (int)Height) - 35;
OS.SetCursorPos(x, y); //Moves the mouse the where I need my click.

Browser.Visibility = Visibility.Visible; //Makes the control visible.
OS.mouse_event(0x02 | 0x04, 0, 0, 0, 0); //Performs the click.

Task.Run(async delegate { //Introduces a short delay to avoid that the mouse moves back before the click occures.
  await Task.Delay(100); //.net framework 4.5 is needed to delay it like this.
  OS.SetCursorPos(pos.X, pos.Y); //Moves the mouse back to it's original position.
});

No comments:

Post a Comment