共用方式為


如何模擬鍵盤事件

Windows Forms 提供以程式設計方式模擬鍵盤輸入的數個選項。 本文將概述這些選項。

使用 SendKeys

Windows Forms 提供 System.Windows.Forms.SendKeys 類別,以便將按鍵傳送至使用中的應用程式。 有兩種方法可將按鍵傳送至應用程式: SendKeys.SendSendKeys.SendWait。 這兩種方法之間的差異在於,SendWait 在傳送按鍵時會封鎖目前的執行緒,等待回應,而 Send 則不會。 如需 SendWait 的詳細資訊,請參閱將按鍵傳送至不同的應用程式

謹慎

如果您的應用程式是要搭配各種鍵盤進行國際使用,則 使用 SendKeys.Send 可能會產生無法預期的結果,並應避免。

在幕後, SendKeys 使用較舊的 Windows 實作來傳送輸入,這可能會在 Windows 上失敗,因為 Windows 預期應用程式未以系統管理許可權執行。 如果較舊的實作失敗,程式碼會自動嘗試較新的 Windows 實作來傳送輸入。 此外,當 SendKeys 類別使用新的實作時,將按鍵傳送至另一個應用程式時,SendWait 方法不會再封鎖目前的執行緒。

這很重要

如果不論作業系統為何,應用程式都需要一致的行為,您可以強制 SendKeys 類別使用新的實作,方式是將下列應用程式設定加入 app.config 檔中。

<appSettings>
  <add key="SendKeys" value="SendInput"/>
</appSettings>

若要強制 SendKeys 類別使用之前的實作,請改用 "JournalHook" 值。

將按鍵動作傳送至相同的應用程式

請呼叫 SendKeys.Send 類別的 SendKeys.SendWaitSendKeys 方法。 應用程式的作用中控件會收到指定的擊鍵。

下列程式代碼範例會使用 Send 模擬一起按下 Alt 鍵和 向下鍵 。 這些按鍵會導致 ComboBox 控制項顯示其下拉式清單。 此範例會假設有 ButtonComboBoxForm

private void button1_Click(object sender, EventArgs e)
{
    comboBox1.Focus();
    SendKeys.Send("%+{DOWN}");
}
Private Sub Button1_Click(sender As Object, e As EventArgs)
    ComboBox1.Focus()
    SendKeys.Send("%+{DOWN}")
End Sub

將按鍵動作傳送至不同的應用程式

SendKeys.SendSendKeys.SendWait 方法會將按鍵傳送至使用中的應用程式,這通常是您傳送按鍵的應用程式。 若要將按鍵傳送至另一個應用程式,您必須先啟動它。 由於沒有啟動另一個應用程式的受控方法,您必須使用原生 Windows 方法將焦點放在其他應用程式上。 下列程式碼範例使用平台叫用呼叫 FindWindowSetForegroundWindow 方法,以啟動 [小算盤] 應用程式視窗,然後再呼叫 Send 對 [小算盤] 應用程式發出一連串計算。

下列程式代碼範例會使用 Send 在 Windows 計算機應用程式中模擬按鍵。 它會先搜尋標題為 Calculator 的應用程式視窗,然後加以啟動。 啟動之後,會傳送按鍵來計算 10 加上 10。

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

private void button1_Click(object sender, EventArgs e)
{
    IntPtr calcWindow = FindWindow(null, "Calculator");

    if (SetForegroundWindow(calcWindow))
        SendKeys.Send("10{+}10=");
}
<Runtime.InteropServices.DllImport("USER32.DLL", CharSet:=Runtime.InteropServices.CharSet.Unicode)>
Public Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr : End Function

<Runtime.InteropServices.DllImport("USER32.DLL")>
Public Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean : End Function

Private Sub Button1_Click(sender As Object, e As EventArgs)
    Dim hCalcWindow As IntPtr = FindWindow(Nothing, "Calculator")

    If SetForegroundWindow(hCalcWindow) Then
        SendKeys.Send("10{+}10=")
    End If
End Sub

使用 OnEventName 方法

模擬鍵盤事件最簡單的方式,是在引發事件的物件上呼叫方法。 大部分事件都有叫用它們的對應方法,其名稱為 On 模式,後面接著 EventName,例如 OnKeyPress。 通常只有在自訂控制項和表單內才能使用這個選項,因為這些方法受到保護,無法從控制項或表單的内容外存取。

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

  • OnKeyDown
  • OnKeyPress
  • OnKeyUp

如需這些事件的詳細資訊,請參閱 使用鍵盤事件

另請參閱