【发布时间】:2017-04-17 10:05:09
【问题描述】:
我有一个控制台应用程序,它应该在 MSPaint 中绘制一张随机图片(鼠标向下 -> 让光标随机绘制一些东西 -> 鼠标向上。这就是我到目前为止所拥有的(我在 Main 方法中添加了 cmets更好地理解我想要实现的目标):
[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)));
}
我从here得到了这个点击模拟的代码。
点击被模拟,但它没有绘制任何东西。似乎单击在 MSPaint 中不起作用。光标变为 MSPaint 的“十字”,但正如我所提到的......点击似乎不起作用。
FindWindow 将hwndMain 的值设置为值0。将参数mspaint 更改为MSPaintApp 不会改变任何内容。 hwndMain 的值保持为 0。
如果有帮助,这是我的OpenPaint() 方法:
private static void OpenPaint()
{
Process.process = new Process();
process.StartInfo.FileName = "mspaint.exe";
process.StartInfo.WindowStyle = "ProcessWindowStyle.Maximized;
process.Start();
}
我做错了什么?
【问题讨论】:
-
第一步:尝试它是否与 Paint 以外的其他应用程序配合得更好,然后报告!
-
嗨!我喜欢这个问题并且很好奇 - 你是否已经找到了答案或者这仍然是开放的?如果您现在还没有找到答案,我今晚会亲自尝试。
-
@TripleEEE 我还没有找到答案。我不能检查,因为我病了..
-
嗨@diiN_ 刚刚发布了一个答案;)
标签: c# click mouseevent cursor-position