如何在已启动的进程上模拟鼠标单击

时间:2014-02-12 10:36:25

标签: c# pinvoke

我正在尝试使用Process.Start()通过C#打开一个应用程序,然后在应用程序上模拟鼠标点击。

当我运行应用程序时,左上角会出现鼠标点击,这不是我想要的。

public partial class Form1 : Form
{
    [DllImport("user32.dll", CharSet = CharSet.Auto,
                             CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(uint dwFlags, int dx, int dy,
                                          int dwData, int dwExtraInfo);
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

    private const int MOUSEEVENTF_ABSOLUTE = 0x8000;
    private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
    private const int MOUSEEVENTF_LEFTUP = 0x0004;
    private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
    private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
    private const int MOUSEEVENTF_MOVE = 0x0001;
    private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
    private const int MOUSEEVENTF_RIGHTUP = 0x0010;
    private const int MOUSEEVENTF_WHEEL = 0x0800;
    private const int MOUSEEVENTF_XDOWN = 0x0080;
    private const int MOUSEEVENTF_XUP = 0x0100;

    private void button1_Click(object sender, EventArgs e)
    {
        new Thread(() =>
        {
            AddTextToListBox1(label1);            
        }).Start();
        new Thread(() =>
        {
           // AddTextToListBox2(label2);
        }).Start();
    }

    private void AddTextToListBox1(Label label)
    {
        if (label1.InvokeRequired)
        {
            stringDelegate sd = new stringDelegate(AddTextToListBox1);
            this.Invoke(sd, new object[] { label1 });
        }
        else
        {
            label1.Text = this.ToString()+"Hi";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "C://xyz//xyz.exe";
            p.Start();
            IntPtr hwnd = p.MainWindowHandle;
        }
    }

    private void AddTextToListBox2(Label label)
    {
        if (label1.InvokeRequired)
        {
            stringDelegate sd = new stringDelegate(AddTextToListBox2);
            this.Invoke(sd, new object[] { label1 });
        }
        else
        {
            label2.Text = "done";
            Thread.Sleep(6000);
            int X = 579;
            int Y = 637;
            mouse_event(MOUSEEVENTF_ABSOLUTE| MOUSEEVENTF_MOVE, X, Y, 0, 0);
            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0);              
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为mouse_event只会在当前应用中引发事件,因为它不会在params上使用hwnd。我在这方面的经验很少,但我做了一些研究。看看SendMessage函数。

MSDN article

  

将指定的消息发送到一个或多个窗口。   SendMessage函数调用指定窗口的窗口过程   并且在窗口过程处理完消息之前不会返回。

您可以使用它发送许多消息,包括鼠标事件