I using SendInput to simulate mouse input and so far I can successf开发者_JS百科ully simulate left, right and middle clicks. However, I cannot seem to simulate the xButtons properly. I am defining an input structure as follows:
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 is defined as follows, and I believe this is where the problem is.
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;
}
}
It turns out I was trying to specify which button was pressed in the wrong place. i.mi.dwFlags
should only specify either Win32.MOUSEEVENTF.XDOWN
or Win32.MOUSEEVENTF.XUP
. The button pressed should be set using i.mi.mouseData
.
So to simulate x button input I would do the following:
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()));
精彩评论