0

I am using the following code from How to simulate Mouse Click in C#? and I have found that it does not work. Here is the code:

    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]

    public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint 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 void DoMouseClick()
    {
        mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 882, 554, 0, 0);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoMouseClick();
    }

I have also tried replacing mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENT_LEFTUP... with mouse_event(MOUSEEVENTF_LEFTDOWN & MOUSEEVENT_LEFTUP... but still no luck. Other people have had success with this... Why am I not?

Community
  • 1
  • 1
Liam McInroy
  • 4,339
  • 5
  • 32
  • 53

1 Answers1

5

You should not use mouse_event(), it has been superseded by SendInput().

There's a good reason for that, the return type for mouse_event() is void. There isn't any way that Windows can tell you that you are doing it wrong. SendInput returns UINT and reports an error by returning 0 and exposing the error code through GetLastError.

And you are definitely doing it wrong. Sending a mouse event that has the button simultaneously up and down doesn't make sense. You need to call it twice; down first, up next.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536