2011-11-25 428 views
32

我想要做的是操縱鼠標。這對於我自己的目的將是一個簡單的宏。所以它會將我的鼠標移動到屏幕上的某個位置,然後像點擊某個間隔一樣點擊。如何在屏幕上的某個位置模擬鼠標點擊?

+1

Would [this](http://stackoverflow.com/questions/8242409/simulate-mouse-clicks-at-a-certain-position-on-inactive-window-in-c-sharp/8242484#8242484)成爲你需要的東西?另外,正如有人在評論中提出的建議,您可能想使用UIAutomation。 – Nasreddine

+1

感謝工作:) – MonsterMMORPG

+1

好吧不太好工作。我如何設置點擊持續時間。像100毫秒保持按下鼠標 – MonsterMMORPG

回答

43

這裏是正在使用的非託管函數來模擬鼠標點擊代碼:

//This is a replacement for Cursor.Position in WinForms 
[System.Runtime.InteropServices.DllImport("user32.dll")] 
static extern bool SetCursorPos(int x, int y); 

[System.Runtime.InteropServices.DllImport("user32.dll")] 
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); 

public const int MOUSEEVENTF_LEFTDOWN = 0x02; 
public const int MOUSEEVENTF_LEFTUP = 0x04; 

//This simulates a left mouse click 
public static void LeftMouseClick(int xpos, int ypos) 
{ 
    SetCursorPos(xpos, ypos); 
    mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0); 
    mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0); 
} 

要在特定的時間內按住鼠標,您可以Sleep()正在執行該功能,例如線程:

mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0); 
System.Threading.Thread.Sleep(1000); 
mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0); 

上面的代碼將保持加壓1秒鐘鼠標除非用戶按壓釋放鼠標按鈕。 此外,請確保不要在主UI線程上執行此代碼,因爲它會導致掛起

+1

工作這是比我在這裏看到的其他解決方案更簡單。謝謝 – Yablargo

+0

此代碼可以正常工作,將指針指向屏幕上的所需座標,但由於某種原因,點擊對我無效。任何想法爲什麼? – john

+0

在這裏您可以獲得其他鼠標按鈕的代碼:https://msdn.microsoft.com/en-us/library/windows/desktop/ms646260(v=vs.85).aspx – Li3ro

7

您可以按XY位置移動。下面的例子:

windows.Forms.Cursor.Position = New System.Drawing.Point(Button1.Location.X + Me.Location.X + 50, Button1.Location.Y + Me.Location.Y + 30) 

要點擊,可以使用下面的代碼:

using System.Runtime.InteropServices; 

private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002; 
private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004; 
[DllImport("user32.dll")] 
    private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData,    uint dwExtraInf); 
private void btnSet_Click(object sender, EventArgs e) 
    { 
     int x = Convert.ToInt16(txtX.Text);//set x position 
     int y = Convert.ToInt16(txtY.Text);//set y position 
     Cursor.Position = new Point(x, y); 
     mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);//make left button down 
     mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//make left button up 
    } 

感謝JOHNYKUTTY

+1

問題是在WPF,而不是形式。 – Vlad

+1

不起作用:windows.Forms.Cursor.Position =新的System.Drawing.Point(Button1.Location.X + Me.Location.X + 50,Button1.Location.Y + Me.Location.Y + 30)。我也嘗試過這種形式沒有提到不會在wpf – MonsterMMORPG