2015-07-11 57 views
0

我想構建一個簡單的應用程序,它所做的只是點擊Chrome瀏覽器中的特定位置。鼠標點擊從c#應用程序的鉻

我開始從代碼的過程

var proc = Process.Start("chrome.exe", 
"https://www.youtube.com/results?search_query=" + textBox1.Text); 

現在我想在它的鼠標點擊。

這是我曾嘗試

private void buttonGO_Click(object sender, EventArgs e) 
    { 
     IntPtr iHandle = FindWindow(null, "Chrome"); 
     if (iHandle != IntPtr.Zero) 
     { 
      SetForegroundWindow(iHandle); 
      Thread.Sleep(2000); 
      moveToPos(30000, 19500); 
      Thread.Sleep(500); 
      performClick(30000, 19500); 
     } 
    } 

    private void performClick(uint x, uint y) 
    { 
     SetCursorPos(x, y); 
     mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN, x, y, 0, UIntPtr.Zero); 
     Thread.Sleep(200); 
     mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTUP, x, y, 0, UIntPtr.Zero); 
    } 
    private void moveToPos(uint x, uint y) 
    { 
     mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE, x, y, 0, UIntPtr.Zero); 
    } 

但它無法找到的窗口。 有誰知道這個?

回答

0

你可以用這個嘗試:

private void buttonGO_Click(object sender, EventArgs e) 
{ 
    // Get all chrome processes 
    Process[] chromeProcesses = Process.GetProcessesByName("chrome"); 
    Process uiProcess = null; 
    foreach (Process process in chromeProcesses) 
    { 
     // Assuming you've opened chrome only once, the UI process will have MainWindowHandle, so get its reference and break out of loop 
     if (process.MainWindowHandle != IntPtr.Zero) 
     { 
      uiProcess = process; 
      break; 
     } 
    } 

    if (uiProcess == null) 
     return; 

    // Do your stuff here 
    IntPtr iHandle = uiProcess.MainWindowHandle; 
    if (iHandle != IntPtr.Zero) 
    { 
     SetForegroundWindow(iHandle); 
     Thread.Sleep(2000); 
     moveToPos(30000, 19500); 
     Thread.Sleep(500); 
     performClick(30000, 19500); 
    } 
} 

另外,如果要執行很多自動化鼠標點擊動作,嘗試AutoIt3庫,它非常適合這樣的事情。