Windows Form 提供使用和修改鍵盤輸入的功能。 取用索引鍵是指處理方法或事件處理常式內的索引鍵,讓其他方法與事件進一步向下訊息佇列不會收到索引鍵值。 此外,修改索引鍵是指修改索引鍵的值,讓訊息佇列中進一步的方法和事件處理常式會收到不同的金鑰值。 本文說明如何完成這些工作。
.NET 7 和 .NET 6 的桌面指南檔正在進行建構。
在
KeyPress
事件處理常式中,將
KeyPressEventArgs
類別的
Handled
屬性設定為
true
。
在
KeyDown
事件處理常式中,將
KeyEventArgs
類別的
Handled
屬性設定為
true
。
在
KeyDown
事件處理常式中設定
Handled
屬性,並不會防止引發目前按鍵的
KeyPress
和
KeyUp
事件。 為了這個目的,請使用
SuppressKeyPress
屬性。
下列範例會
KeyPress
處理 事件以取用
A
和
a
字元索引鍵。 這些索引鍵無法輸入到文字方塊中:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
if (e.KeyChar == 'a' || e.KeyChar == 'A')
e.Handled = true;
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
If e.KeyChar = "a"c Or e.KeyChar = "A"c Then
e.Handled = True
End If
End Sub
修改標準字元索引鍵
在
KeyPress
事件處理常式中,將
KeyPressEventArgs
類別的
KeyChar
屬性設定為新的字元按鍵值。
下列範例會處理 事件,
KeyPress
將任何
A
和
a
字元索引鍵變更為
!
:
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
if (e.KeyChar == 'a' || e.KeyChar == 'A')
e.KeyChar = '!';
e.Handled = false;
Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs)
If e.KeyChar = "a"c Or e.KeyChar = "A"c Then
e.KeyChar = "!"c
e.Handled = False
End If
End Sub
修改非字元索引鍵
您只能藉由繼承自 控制項並覆寫
PreProcessMessage
方法,修改非字元按鍵按下。 當輸入
Message
傳送至控制項時,會在控制項引發事件之前進行處理。 您可以攔截這些訊息來修改或封鎖這些訊息。
下列程式碼範例示範如何使用
WParam
參數的
Message
屬性來變更按下的按鍵。 此程式碼會偵測
F1 到 F10
的索引鍵,並將索引鍵轉譯為介於
0
到
9
(的數值索引鍵,其中
F10
對應至
0
) 。
public override bool PreProcessMessage(ref Message m)
const int WM_KEYDOWN = 0x100;
if (m.Msg == WM_KEYDOWN)
Keys keyCode = (Keys)m.WParam & Keys.KeyCode;
// Detect F1 through F9.
m.WParam = keyCode switch
Keys.F1 => (IntPtr)Keys.D1,
Keys.F2 => (IntPtr)Keys.D2,
Keys.F3 => (IntPtr)Keys.D3,
Keys.F4 => (IntPtr)Keys.D4,
Keys.F5 => (IntPtr)Keys.D5,
Keys.F6 => (IntPtr)Keys.D6,
Keys.F7 => (IntPtr)Keys.D7,
Keys.F8 => (IntPtr)Keys.D8,
Keys.F9 => (IntPtr)Keys.D9,
Keys.F10 => (IntPtr)Keys.D0,
_ => m.WParam
// Send all other messages to the base method.
return base.PreProcessMessage(ref m);
Public Overrides Function PreProcessMessage(ByRef m As Message) As Boolean
Const WM_KEYDOWN = &H100
If m.Msg = WM_KEYDOWN Then
Dim keyCode As Keys = CType(m.WParam, Keys) And Keys.KeyCode
Select Case keyCode
Case Keys.F1 : m.WParam = CType(Keys.D1, IntPtr)
Case Keys.F2 : m.WParam = CType(Keys.D2, IntPtr)
Case Keys.F3 : m.WParam = CType(Keys.D3, IntPtr)
Case Keys.F4 : m.WParam = CType(Keys.D4, IntPtr)
Case Keys.F5 : m.WParam = CType(Keys.D5, IntPtr)
Case Keys.F6 : m.WParam = CType(Keys.D6, IntPtr)
Case Keys.F7 : m.WParam = CType(Keys.D7, IntPtr)
Case Keys.F8 : m.WParam = CType(Keys.D8, IntPtr)
Case Keys.F9 : m.WParam = CType(Keys.D9, IntPtr)
Case Keys.F10 : m.WParam = CType(Keys.D0, IntPtr)
End Select
End If
Return MyBase.PreProcessMessage(m)
End Function
使用鍵盤 (Windows Forms .NET) 概觀
使用鍵盤事件 (Windows Forms .NET)
KeyDown
KeyPress