2014-02-12 45 views
-2

我试图通过C#使用Process.Start()打开应用程序,然后模拟鼠标单击该应用程序。如何在已启动的进程上模拟鼠标点击

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

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

如果你想要做什么比一个单一的点击鼠标更复杂,你可能要考虑使用UI自动化系统,而不是试图制作原始活动。 –

+0

现在我只想简单的点击鼠标。 – Sarfaraz

+0

为什么你不能使用UIAutomation? –

回答

0

我想是因为它并不需要hwnd上PARAMS mouse_event只提高在当前的应用程序事件。我在这方面的经验很低,但我已经做了一些研究。看看SendMessage函数。

MSDN article

发送指定的消息到窗口或窗口。 SendMessage函数调用指定窗口 的窗口过程,直到窗口过程处理完消息后才会返回。

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