Windows Forms 應用中,鼠標與鍵盤事件是人機交互的核心。本文系統講解六大鼠標事件、三大鍵盤事件的委託綁定差異、事件參數獲取技巧,並提供兩個可直接運行的完整示例項目。
| 事件名 | 觸發時機 | 委託類型 | 參數類 | 命名空間 |
|---|---|---|---|---|
| MouseHover | 鼠標懸停靜止 | EventHandler | EventArgs | System |
| MouseEnter | 鼠標進入控件 | |||
| MouseLeave | 鼠標離開控件 | |||
| MouseMove | 鼠標移動 | MouseEventHandler | MouseEventArgs | System.Windows.Forms |
| MouseDown | 按下鼠標鍵 | |||
| MouseUp | 釋放鼠標鍵 |
// 前三類事件(無座標信息)
button1.MouseLeave += new System.EventHandler(button1_MouseLeave);
private void button1_MouseLeave(object sender, EventArgs e) { }
//後三類事件(包含座標/按鍵信息)
button1.MouseMove += new MouseEventHandler(button1_MouseMove);
private void button1_MouseMove(object sender, MouseEventArgs e) {
// e.X, e.Y 獲取座標
// e.Button 判斷按鍵
}
using System;
using System.Windows.Forms;
public class Form1 : Form {
public Form1() {
this.Text = "C# 鼠標事件演示";
this.ClientSize = new System.Drawing.Size(400, 300);
// 綁定窗體級事件
this.MouseMove += new MouseEventHandler(Form1_MouseMove);
this.MouseDown += new MouseEventHandler(Form1_MouseDown);
}
private void Form1_MouseMove(object sender, MouseEventArgs e) {
// 實時顯示座標於標題欄
this.Text = $"當前鼠標位置: ({e.X}, {e.Y})";
}
private void Form1_MouseDown(object sender, MouseEventArgs e) {
string btn = e.Button switch {
MouseButtons.Left => "左鍵",
MouseButtons.Right => "右鍵",
MouseButtons.Middle => "中鍵",
_ => "其他"
};
MessageBox.Show($"按下了鼠標{btn}!", "鼠標按鍵檢測");
}
[STAThread]
static void Main() {
Application.Run(new Form1());
}
}
MouseButtons.Left/Right/Middle/XButton1/XButton2| 事件 | 委託 | 參數類 | 適用場景 |
|---|---|---|---|
| KeyDown | KeyEventHandler | KeyEventArgs | 功能鍵、組合鍵、非字符鍵 |
| KeyUp | KeyEventHandler | KeyEventArgs | 釋放按鍵邏輯 |
| KeyPress | KeyPressEventHandler | KeyPressEventArgs | 字符輸入(含大小寫、輸入法) |
private void Form1_KeyUp(object sender, KeyEventArgs e) {
// KeyCode 返回物理鍵值(不受 Shift 影響)
MessageBox.Show($"按鍵代碼: {e.KeyCode}", "按鍵檢測");
// 組合鍵檢測
if (e.Control && e.KeyCode == Keys.S) {
// Ctrl+S 保存邏輯
}
}
public class Form1 : Form {
public Form1() {
this.Text = "C# 鍵盤事件演示";
this.KeyUp += new KeyEventHandler(Form1_KeyUp);
// 必須設置 KeyPreview=true 才能在窗體級捕獲子控件按鍵
this.KeyPreview = true;
}
private void Form1_KeyUp(object sender, KeyEventArgs e) {
MessageBox.Show(e.KeyCode.ToString(), "您按下的鍵為:");
}
[STAThread]
static void Main() {
Application.Run(new Form1());
}
}
PointToScreen/PointToClient 處理跨控件座標Form.KeyPreview = true 讓窗體優先處理按鍵掌握委託綁定差異、參數類屬性、座標系與按鍵枚舉是高效處理輸入事件的關鍵。建議將兩個示例項目納入代碼片段庫,新項目可直接復用核心邏輯。對於複雜交互場景(拖拽、繪圖、遊戲),可在此基礎上構建狀態機管理事件流。