2014-02-12 42 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函數調用指定窗口 的窗口過程,直到窗口過程處理完消息後纔會返回。

您可以發送與它的許多消息,包括鼠標事件