Search code examples
c#mouseclick-eventonkeypress

Simulate Mouse Click when key is pressed


I´m trying to simulate a mouse click when certain key is pressed.

I tried this:

[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 = 0x08; 

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
         case Keys.Insert:

             Point pt = Cursor.Position;
             int X = Cursor.Position.X;
             int Y = Cursor.Position.Y;

             mouse_event(MOUSEEVENTF_RIGHTDOWN, X, Y, 0, 0);
             break;
    }

It doesn't seems to be working, and I couldn't find any other solution.


Solution

  • First make sure the Form KeyPreview property is set to True

    enter image description here

    To do the click simulation you need to call MOUSEEVENTF_RIGHTDOWN and MOUSEEVENTF_RIGHTUP like so. (also notice i use uint along the way)

    [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;
    
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode)
        {
            case Keys.Insert:
    
                int X = Cursor.Position.X;
                int Y = Cursor.Position.Y;
    
                mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, (uint)X, (uint)Y, 0, 0);
                break;
        }
    }