I am trying to automatically draw in a program similar to paint by simulating mouse movement and clicks with user32.dll in Windows 7.
Here’s what I have and how I use it:
Setup
[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
[Flags]
public enum MouseEventFlags
{
LEFTDOWN = 0x00000002,
LEFTUP = 0x00000004,
MIDDLEDOWN = 0x00000020,
MIDDLEUP = 0x00000040,
MOVE = 0x00000001,
ABSOLUTE = 0x00008000,
RIGHTDOWN = 0x00000008,
RIGHTUP = 0x00000010
}
public void LeftMouseDown()
{
mouse_event((int)(MouseEventFlags.LEFTDOWN), Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
public void LeftMouseUp()
{
mouse_event((int)(MouseEventFlags.LEFTUP), Cursor.Position.X, Cursor.Position.Y, 0, 0);
}
When Drawing
foreach (var contour in contours)
{
LeftMouseDown();
foreach (var point in contour)
{
var x = point.X + offsetX;
var y = point.Y + offsetY;
Cursor.Position = new Point(x, y);
//LeftMouseDown();
System.Threading.Thread.Sleep(2);
}
LeftMouseUp();
}
What I’m trying to simulate is the mouse being clicked and held, moved around to a bunch of points in each contour and then let up before moving on to the next contour.
The problem, is that this just holds the mouse button down for the first movement and then lets it up.
TL;DR
How can I keep the mouse left click down when the mouse is being moved around programatically?
I am trying to simulate drawing in a third party app. (Microsoft LINQ’s Whiteboard, the IM client.)
Summarizing the comment trail: this has not the expected result because the code only simulates mouse clicks, not mouse motion. Moving the cursor with Cursor.Position directly changes the cursor position, bypassing the Windows input event queue. So doesn’t generate any notifications (WM_MOUSEMOVE messages) to the window that has the focus.
Fix by adding a MouseMove() method to the helper class that uses mouse_event() with MouseEventFlags.MOVE