範例實作:執行時僅允許在文字方塊輸入數字;若輸入非數字,將該字元顯示於表單標題列,並取消輸入(文字方塊不顯示)。
核心程式碼:
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar))
{
this.Text = e.KeyChar.ToString(); // 顯示於標題列
e.Handled = true; // 取消輸入
}
}
KeyChar != 8 排除 Backspace 鍵;char.IsDigit 判斷是否為數字;e.Handled = true 標記事件已處理,阻止字元進入控制項。