如何模擬滑鼠事件 (Windows Forms .NET)

模擬 Windows Forms 中的滑鼠事件並不像模擬鍵盤事件那麼直接。 Windows Forms 不提供協助程式類別來移動滑鼠並叫用按兩下滑鼠動作。 控制滑鼠的唯一選項是使用原生 Windows 方法。 如果您正在使用自定義控件或表單,您可以模擬滑鼠事件,但無法直接控制滑鼠。

事件

大部分事件都有一個對應的方法來叫用它們,其名稱為 On ,後面接著 EventName,例如 OnMouseMove。 這個選項只能在自定義控件或窗體內使用,因為這些方法受到保護,而且無法從控件或窗體的內容外部存取。 使用 這類 OnMouseMove 方法的缺點是它實際上不會控制滑鼠或與控件互動,而只會引發相關聯的事件。 例如,如果您想要模擬將滑鼠停留在 中的 ListBox專案上, OnMouseMove 而且 ListBox 不會以可視化方式回應游標下反白顯示的專案。

這些受保護的方法可用來模擬滑鼠事件。

  • OnMouseDown
  • OnMouseEnter
  • OnMouseHover
  • OnMouseLeave
  • OnMouseMove
  • OnMouseUp
  • OnMouseWheel
  • OnMouseClick
  • OnMouseDoubleClick

如需這些事件的詳細資訊,請參閱 使用滑鼠事件 (Windows Forms .NET)

叫用按一下

考慮到大部分控件會在按兩下時執行某些動作,例如呼叫使用者程式代碼的按鈕,或複選框變更其核取狀態,Windows Forms 提供簡單的方法來觸發單擊。 某些控件,例如下拉式方塊,在單擊並模擬按兩下時不會執行任何特殊動作,對控件沒有任何作用。

PerformClick

介面 System.Windows.Forms.IButtonControl 會提供 PerformClick 模擬單擊控件的方法。 System.Windows.Forms.ButtonSystem.Windows.Forms.LinkLabel 控件都會實作這個介面。

button1.PerformClick();
Button1.PerformClick()

InvokeClick

使用表單自定義控制項時,請使用 InvokeOnClick 方法來模擬滑鼠點選。 這是受保護的方法,只能從窗體或衍生的自定義控件中呼叫。

例如,下列程式代碼會從 button1按一下複選框。

private void button1_Click(object sender, EventArgs e)
{
    InvokeOnClick(checkBox1, EventArgs.Empty);
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    InvokeOnClick(CheckBox1, EventArgs.Empty)
End Sub

使用原生 Windows 方法

Windows 提供方法,您可以呼叫 以模擬滑鼠移動,然後按兩下 ,例如 User32.dll SendInputUser32.dll SetCursorPos。 下列範例會將滑鼠游標移至控件的中心:

[DllImport("user32.dll", EntryPoint = "SetCursorPos")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetCursorPos(int x, int y);

private void button1_Click(object sender, EventArgs e)
{
    Point position = PointToScreen(checkBox1.Location) + new Size(checkBox1.Width / 2, checkBox1.Height / 2);
    SetCursorPos(position.X, position.Y);
}
<Runtime.InteropServices.DllImport("USER32.DLL", EntryPoint:="SetCursorPos")>
Public Shared Function SetCursorPos(x As Integer, y As Integer) As Boolean : End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim position As Point = PointToScreen(CheckBox1.Location) + New Size(CheckBox1.Width / 2, CheckBox1.Height / 2)
    SetCursorPos(position.X, position.Y)
End Sub

另請參閱