按下键时模拟鼠标单击

Simulate Mouse Click when key is pressed

我正在尝试模拟按下某个键时的鼠标点击。

我试过这个:

[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;
    }

它似乎不起作用,我找不到任何其他解决方案。

首先确保表格 KeyPreview 属性 设置为 True

要进行点击模拟,您需要像这样调用 MOUSEEVENTF_RIGHTDOWNMOUSEEVENTF_RIGHTUP(还要注意我一直使用 uint)

[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;
    }
}