在 C# WinForms 中,若希望使用者在輸入框按下 Enter 鍵時自動觸發某個按鈕,可先將表單的 KeyPreview 設為 true,讓表單能接收鍵盤事件,再處理 KeyDown 或 KeyPress。
以下範例在 textBox1 的 KeyDown 事件中判斷是否按下 Enter:
this.KeyDown += new KeyEventHandler(textBox1_KeyDown);
private void textBox1_KeyDown(object sender, KeyEventArgs e){ if (e.KeyCode == Keys.Enter) { this.L_login.Focus(); L_login_Click(this, new EventArgs()); }}
這樣當使用者按下 Enter 時,焦點會移到登入按鈕,並直接呼叫按鈕的 Click 事件,達到鍵盤快速操作的效果。