Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate mouse clicks at a certain position on inactive window in C#

Here is the original question but it is considered to java: Simulate mouse clicks at a certain position on inactive window in Java?

Anyways, I'm building a bot to run in the background. This bot requires me to click. Of course, I want to be able to do other things while the bot is running.

So I was wondering if it was possible for me to simulate a mouse click at a certain position on an inactive window.

If this is possible, I would greatly appreciate it if any of you could help me.

Thanks!

like image 460
Ritam Nemira Avatar asked Nov 23 '11 12:11

Ritam Nemira


1 Answers

Yes it is possible, here's the code I used for a previous school project:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

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

//This simulates a left mouse click
public static void LeftMouseClick(Point position)
{
    Cursor.Position = position;
    mouse_event(MOUSEEVENTF_LEFTDOWN, position.X, position.Y, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP, position.X, position.Y, 0, 0);
}

EDIT : It seems that the mouse_event function was replaced by SendInput() but it still works (Windows 7 and earlier)

like image 158
Nasreddine Avatar answered Oct 14 '22 08:10

Nasreddine