模拟鼠标按下键时单击

时间:2016-10-29 14:30:50

标签: c# mouseclick-event onkeypress

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

我试过了:

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

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

1 个答案:

答案 0 :(得分:0)

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

enter image description here

要进行点击模拟,您需要像这样调用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;
    }
}