[英]C# How can I clear a textbox when the backspace button is pressed
我正在使用C#並在Winform程序上工作,當用戶點擊文本框並按下退格按鈕時我想清除文本框而不是一次刪除一個字符。 我怎樣才能做到這一點?
非常感謝史蒂夫
您可以訂閱KeyPress事件並清除發件人的文本:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 8)
{
((TextBox)sender).Clear();
}
}
private void button1_Click(object sender, EventArgs e)
{
int textlength = textBox1.Text.Length;
if (textlength > 0)
{
textBox1.Text = textBox1.Text.Substring(0, textlength - 1);
}
textBox1.Focus();
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.SelectionLength = 0;
}
如果這是一個用戶將輸入文本的字段,請考慮一些用戶(比如我)在打出拼寫錯誤時有自然傾向於打Backspace。 如果這樣做清除了我輸入的所有內容,我會覺得很煩人。
作為替代方案,如果他們執行Shift-Backspace,您可以添加此行為。 下面的代碼將刪除Shift-Backspace上插入符號之前的所有內容,但如果用戶選擇了文本,則還會保留僅刪除選擇內容的預期行為:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// if shift-backspace is pressed and nothing is selected,
// delete everything before the caret
if (e.Shift && e.KeyCode == Keys.Back && textBox1.SelectionLength == 0)
{
textBox1.Text = textBox1.Text.Substring(textBox1.SelectionStart);
e.Handled = true;
}
}
訂閱KeyDown
事件,當按下的鍵等於退格鍵時,您只需清除文本框。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.