2012-07-27 177 views
3

是否可以在沒有實際點擊的情況下模擬Click模擬點擊不點擊

例如我想在運行的計算器上用Click鼠標靜止。這可能嗎?

+0

你想要做什麼語言?你標籤winapi和C,C++或C#都是有效的候選人。另外,你想要點擊什麼?一個按鈕?一個特定的座標? – rrhartjr 2012-07-27 14:19:17

+0

沒關係。他們中的任何一個都OK :) 但我更喜歡C#,C++和Python。 – MBZ 2012-07-27 14:20:03

+0

@MBZ那麼,最好在這裏檢查一下:http://stackoverflow.com/questions/2416748/how-to-simulate-mouse-click-in-c – 2012-07-27 14:46:27

回答

8

如果您只是試圖在相當典型的標籤,字段和按鈕應用程序中單擊按鈕,則可以使用一點P/Invoke將FindWindowSendMessage用於控件。

如果您還不熟悉Spy ++,現在可以開始了!

它與Visual Studio 2012 RC打包在一起:C:\Program Files\Microsoft Visual Studio 11.0\Common7\Tools。它應該類似地發現其他版本。

試試這個作爲控制檯C#應用程序:

class Program 
{ 
    [DllImport("user32.dll", SetLastError = true)] 
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 

    [DllImport("user32.dll")] 
    static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow); 

    [DllImport("user32.dll", CharSet = CharSet.Auto)] 
    public static extern IntPtr SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam); 

    private const uint BM_CLICK = 0x00F5; 

    static void Main(string[] args) 
    { 
     // Get the handle of the window 
     var windowHandle = FindWindow((string)null, "Form1"); 

     // Get button handle 
     var buttonHandle = FindWindowEx(windowHandle, IntPtr.Zero, (string)null, "A Huge Button"); 

     // Send click to the button 
     SendMessage(buttonHandle, BM_CLICK, 0, 0); 
    } 
} 

這得到手柄標題 「Form1的」 窗口。使用該句柄,它將獲得窗口內Button的句柄。然後向按鈕控件發送一個類型爲「BM_CLICK」的消息,其中沒有有用的參數。

我用一個測試WinForms應用程序作爲我的目標。一個按鈕和一些代碼後面增加一個計數器。

A Test WinForms App

您應該看到計數器增量當您運行的P/Invoke控制檯應用程序。但是,你會不是看到按鈕動畫。

你也可以使用Spy ++ Message Logger功能。我建議過濾器BM_CLICK,也許WM_LBUTTONDOWN/WM_LBUTTONUP(手動點擊會給你什麼)。

希望有幫助!