I want to create a left mouse click. All i can find anywhere is having to do if the user clicks, i want to create a left mouse click automatically.

7 Years
Discussion Span
Last Post by Steve_Jones
using System;
using System.Runtime.InteropServices;

public class MouseEvents {
    [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);

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

    public MouseEvents() {

    public void DoMouseClick() {
        //user curent cursor position
        DoMouseClick(Cursor.Position.X, Cursor.Position.Y);

    public void DoMouseClick(int x, int y) {
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, x, y, 0, 0);

Add your own methods as needed for the other mouse actions.

Votes + Comments
Solves my problem. Hopefully one day ill be able to write that myself.

A call to PInvoke function 'WindowsFormsApplication2!WindowsFormsApplication2.MouseEvents::mouse_event' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

I got this when i tested it.

It seems like its going with the int x int y overloaded method, when i didnt put any numbers shouldnt it just go with the custom constructor? It brings me to the line of domouseclick int x int y i mean. Not the first domouseclick().

Edited by Steve_Jones: n/a


Sorry, my fault, was old code. Signature should be static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo); Make changes for the unsigned stuff as needed :)

Edited by Momerath: n/a

Votes + Comments
Finishes him helping me.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.