按下→按住→釋放觸發順序:KeyDown → KeyPress → KeyUp。
KeyDown/KeyUp 可捕捉特殊鍵 (Ctrl/Shift/Alt) 及組合鍵,KeyPress 僅字符鍵。
首次按下鍵時觸發。
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;
}
KeyEventArgs 關鍵屬性:
| 屬性 | 說明 |
|---|---|
| Control | Ctrl 是否按下 |
| KeyCode | 鍵盤代碼 (Keys 枚舉) |
| KeyData | 鍵資料 (含修飾鍵) |
| KeyValue | 鍵盤數值 |
| Modifiers | 修飾鍵標誌 (Ctrl/Shift/Alt 組合) |
| Shift | Shift 是否按下 |
釋放鍵時觸發。
private void frmKeyDownUP_KeyUp(object sender, KeyEventArgs e) {
this.ClientSize = new System.Drawing.Size(800, 100);
}
範例:按完鍵自動調整視窗大小。