使用SendInput模拟XButton输入

时间:2011-01-07 10:12:23

标签: c# input mouse sendinput

我使用SendInput来模拟鼠标输入,到目前为止我可以成功模拟左,右和中间点击。但是,我似乎无法正确模拟xButton。我正在定义一个输入结构如下:

Win32.INPUT i = new Win32.INPUT();
            i.type = Win32.INPUTF.MOUSE;
            i.mi.dx = 0;
            i.mi.dy = 0;
            i.mi.mouseData = 0;
            i.mi.time = 0;
            i.mi.dwExtraInfo = UIntPtr.Zero;
            i.mi.dwFlags = MouseButton(e.Button, true);
            Win32.SendInput(1, ref i, System.Runtime.InteropServices.Marshal.SizeOf(new Win32.INPUT()));

MouseButton的定义如下,我相信这就是问题所在。

private Win32.MOUSEEVENTF MouseButton(MouseButtons mb, bool up)
    {
        switch (mb)
        {
            case MouseButtons.Left:
                return up ? Win32.MOUSEEVENTF.LEFTUP : Win32.MOUSEEVENTF.LEFTDOWN;
            case MouseButtons.Right:
                return up ? Win32.MOUSEEVENTF.RIGHTUP : Win32.MOUSEEVENTF.RIGHTDOWN;
            case MouseButtons.Middle:
                return up ? Win32.MOUSEEVENTF.MIDDLEUP : Win32.MOUSEEVENTF.MIDDLEDOWN;
            case MouseButtons.XButton1:
                return up ?  Win32.MOUSEEVENTF.XBUTTON1|Win32.MOUSEEVENTF.XUP  : Win32.MOUSEEVENTF.XBUTTON1 | Win32.MOUSEEVENTF.XDOWN;
            case MouseButtons.XButton2:
                return up ? Win32.MOUSEEVENTF.XBUTTON2 | Win32.MOUSEEVENTF.XUP : Win32.MOUSEEVENTF.XBUTTON2 | Win32.MOUSEEVENTF.XDOWN;
            default:
                return 0u;
        }
    }

1 个答案:

答案 0 :(得分:4)

事实证明我试图指定在错误的位置按下了哪个按钮。 i.mi.dwFlags只应指定Win32.MOUSEEVENTF.XDOWNWin32.MOUSEEVENTF.XUP。按下的按钮应使用i.mi.mouseData设置。

因此,要模拟x按钮输入,我会执行以下操作:

Win32.INPUT i = new Win32.INPUT();
            i.type = Win32.INPUTF.MOUSE;
            i.mi.dx = 0;
            i.mi.dy = 0;
            switch (e.Button)
            {
                case System.Windows.Forms.MouseButtons.XButton1:
                    i.mi.mouseData = (uint)Win32.MOUSEEVENTF.XBUTTON1;
                    break;
                case System.Windows.Forms.MouseButtons.XButton2:
                    i.mi.mouseData = (uint)Win32.MOUSEEVENTF.XBUTTON2;
                    break;
                default:
                    i.mi.mouseData = 0;
                    break;
            }

            i.mi.time = 0;
            i.mi.dwExtraInfo = UIntPtr.Zero;
            i.mi.dwFlags = Win32.MOUSEEVENTF.XUP;
            Win32.SendInput(1, ref i, System.Runtime.InteropServices.Marshal.SizeOf(new Win32.INPUT()));