简体   繁体   中英

Creating a 'Ghost Mouse' to simulate mouse clicks

I know there are already a million threads about this, but I've spent countless hours trying to find a solution and i'm hoping I can find it here instead.

My goal is to create a 'Ghost mouse', meaning that I want to be able to simulate mouse clicks on a certain position in a minimized window, without moving my own cursor our mouse. I want to be able to browse the internet and click on other stuff, while the program does its own thing. This is a feature that many game bots have, but my intention is not to create a bot, but only to experience with.

So far i've managed to simulate mouse clicks, but with my actual mouse.

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

 private const int MOUSEEVENTF_LEFTDOWN = 0x02;
        private const int MOUSEEVENTF_LEFTUP = 0x04;

public static void LeftClick()
        {
            int X = Cursor.Position.X;
            int Y = Cursor.Position.Y;

            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);
        }

 static void Main(string[] args)
        {

 System.Threading.Thread.Sleep(5000);
                Point pt = new Point(1259, 560);
                Cursor.Position = pt;
                LeftClick();

}

As far as I know, calling mouse_event will not click in minimized windows.
You have to use SendMessage WinApi for this.
First, acquire a handle for the process, either using OpenProcess or Process.GetProcessesByName(processName).First().MainWindowHandle, then you may use the following code:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

public const uint WM_LBUTTONDOWN = 0x0201;
public const uint WM_LBUTTONUP = 0x0202;

public static IntPtr makeLParam(int x, int y)
{
    return (IntPtr)((y << 16) | x);
}

public static void sendMouseClick(IntPtr handle, int x, int y)
{
    SendMessage(handle, WM_LBUTTONDOWN, (IntPtr)1, makeLParam(x, y));
    SendMessage(handle, WM_LBUTTONUP, (IntPtr)1, makeLParam(x, y));
}

Please note that this code is a bit old and might not still work. Also, keep in mind the game protections prevents acquiring handles for the game process. In addition, some games might query the mouse position from the windows rather than using the ones provided with SendMessage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM