I have a console application which should paint a random picture in MSPaint (mouse down -> let the cursor randomly paint something -> mouse up. This is what I have so far (I added comments to the Main
method for better understanding what I want to achieve):
[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]
public static extern void mouse_event(long dwFlags, uint dx, uint dy, long cButtons, long dwExtraInfo);
private const int MOUSEEVENTF_LEFTDOWN = 0x201;
private const int MOUSEEVENTF_LEFTUP = 0x202;
private const uint MK_LBUTTON = 0x0001;
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr parameter);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
static IntPtr childWindow;
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
childWindow = handle;
return false;
}
public static void Main(string[] args)
{
OpenPaint(); // Method that opens MSPaint
IntPtr hwndMain = FindWindow("mspaint", null);
IntPtr hwndView = FindWindowEx(hwndMain, IntPtr.Zero, "MSPaintView", null);
// Getting the child windows of MSPaintView because it seems that the class name of the child isn't constant
EnumChildWindows(hwndView, new EnumWindowsProc(EnumWindow), IntPtr.Zero);
Random random = new Random();
Thread.Sleep(500);
// Simulate a left click without releasing it
SendMessage(childWindow, MOUSEEVENTF_LEFTDOWN, new IntPtr(MK_LBUTTON), CreateLParam(random.Next(10, 930), random.Next(150, 880)));
for (int counter = 0; counter < 50; counter++)
{
// Change the cursor position to a random point in the paint area
Cursor.Position = new Point(random.Next(10, 930), random.Next(150, 880));
Thread.Sleep(100);
}
// Release the left click
SendMessage(childWindow, MOUSEEVENTF_LEFTUP, new IntPtr(MK_LBUTTON), CreateLParam(random.Next(10, 930), random.Next(150, 880)));
}
I got this code for the click simulation from here.
The click gets simulated but it doesn't paint anything. It seems that the click doesn't work inside MSPaint. The cursor changes to the "cross" of MSPaint but as I mentioned...the click doesn't seem to work.
FindWindow
sets the value of hwndMain
to value 0. Changing the parameter mspaint
to MSPaintApp
doesn't change anything. The value of hwndMain
stays 0.
If it helps, here is my OpenPaint()
method:
private static void OpenPaint()
{
Process.process = new Process();
process.StartInfo.FileName = "mspaint.exe";
process.StartInfo.WindowStyle = "ProcessWindowStyle.Maximized;
process.Start();
}
What am I doing wrong?