鍵盤按下並釋放過程中會依序觸發三個事件:
KeyDown → KeyPress → KeyUp
KeyDown 與 KeyUp 可捕捉特殊鍵(如 Ctrl、Shift、Alt、功能鍵)與組合鍵,僅在需取得按鍵詳細資訊時使用。
首次按下某個鍵時觸發。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string G_str_Mode = "";
string G_str_text = e.KeyCode + ":" + e.Modifiers + ":" + e.KeyData + ":(" + e.KeyValue + ")";
if (e.Shift) G_str_Mode = "Shift 鍵被按下";
if (e.Control) G_str_Mode = "Ctrl 鍵被按下";
if (e.Alt) G_str_Mode = "Alt 鍵被按下";
this.Text = G_str_text + G_str_Mode;
}
| 屬性 | 說明 |
|---|---|
Control | 是否按下 Ctrl 鍵 |
KeyCode | 取得鍵盤代碼(Keys 列舉) |
KeyData | 取得鍵資料(含修飾鍵) |
KeyValue | 取得鍵盤數值 |
Modifiers | 取得修飾鍵旗標(Ctrl/Shift/Alt 組合) |
Shift | 是否按下 Shift 鍵 |
Alt | 是否按下 Alt 鍵 |
釋放鍵時觸發。
private void frmKeyDownUP_KeyUp(object sender, KeyEventArgs e)
{
this.ClientSize = new System.Drawing.Size(800, 100);
}
KeyPress 僅在輸入字元鍵(字母、數字、符號)時觸發,提供 KeyChar 屬性取得實際字元,適合字元級驗證(如只允許數字輸入)。
KeyDown 判斷 e.Control && e.KeyCode == Keys.S,並設 e.Handled = true 阻止進一步處理。KeyDown/KeyUp 維護按鍵狀態陣列,實現流暢移動控制。KeyPress 攔截非法字元,KeyDown 處理導航鍵(Enter、Tab、Esc)。