[英]C# - How can I block the typing of a letter on a key press?
我有一個帶有OnKeyPress事件的文本框。 在此文本框中,我只希望輸入數字,對於某些特定的字母,例如t或m,我想執行一個代碼,而無需在文本框中鍵入該字母。 我正在嘗試做的小樣本:
//OnKeyPressed:
void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
}
不幸的是,這不會阻止字母的輸入。
將KeyEventArgs的SuppressKeyPress屬性設置為true,如下所示:
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
您可以始終在keyDown事件上運行TryParse,以便在輸入數據時進行驗證。 它為用戶節省了額外的UI交互。
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
int i;
string s = string.Empty;
s += (char)e.KeyValue;
if (!(int.TryParse(s, out i)))
{
e.SuppressKeyPress = true;
}
else if(e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.