Full mouse control emulation using wpf: click, drag, enter, exit
I'm working on a project where I need to use a joystick (DirectInput) to control the mouse pointer inside a wpf application. I need to be able to press/release a mouse button as well as possibly drag across the screen. Preferably this should actually control the mouse, allowing the joystick to be used to control other applications as well. I've got everything figured out on the DirectInput side, but I'm having trouble with the mouse-drag interaction.
This is how I'm doing left-button down:
[DllImport("user32.dll", Set开发者_StackOverflow社区LastError = true)]
static extern uint SendInput(uint nInputs, ref Input pInputs, int cbSize);
...
var aInput = new Input {
type = 0x0,
mouse = new MouseInput {
dwFlags = 0x6,
dwExtraInfo = 0,
mouseData = 0,
time = 0
}
};
SendInput(1, ref aInput, 28);
where Input and MouseInput are as follows:
[StructLayout(LayoutKind.Explicit)]
public struct Input {
[FieldOffset(0)]
public int type; // 4
[FieldOffset(4)]
public MouseInput mouse; // 24
}
[StructLayout(LayoutKind.Explicit)]
public struct MouseInput {
[FieldOffset(0)]
public int dx; // 4
[FieldOffset(4)]
public int dy; // 4
[FieldOffset(8)]
public int mouseData; // 4
[FieldOffset(12)]
public int dwFlags; // 4
[FieldOffset(16)]
public int time; // 4
[FieldOffset(20)]
public int dwExtraInfo; // 4
};
This method works for left/right mouse button down, and System.Windows.Forms.Cursor.Position works well for mouse movement, but I'm not sure how to get a mouse drag rigged up. Any pointers?
See related articles here on SO:
Injecting Mouse Input in WPF Applications
Simulate Mouse/Keyboard Input In WPF
Move the mouse in wpf
EDIT: concerning the specific "drag" need, here is another link (from the NUnitForms project here: http://nunitforms.sourceforge.net/) about a MouseController utility code that contains mouse simulation methods:
http://nunitforms.svn.sourceforge.net/viewvc/nunitforms/trunk/nunitforms/source/NUnitForms/MouseController.cs?view=markup
It has a Drag method. You could test if this works. I know, it's especially designed for WPF, but it's worth a try. Plus, if it's only about mouse mouvement, I don't see a problem if you need to reference Winforms assembly.
Benjamin, I used your code for generating mouse click. I played with the contents and found that setting "dwFlags = 0x3" did the mouse left button click and hold :)
精彩评论