如何停止键盘按键的默认功能?

时间:2017-09-11 20:46:45

标签: c#

我创建了一个TextBox并绑定了 Space 来检查textbox1richtextbox1中的字符串是否相同:

if (e.KeyCode == Keys.Space)
{
    if (richTextBox1.Text.Contains(textBox1.Text))
    {
        richTextBox1.Text = richTextBox1.Text.Replace(textBox1.Text + " ", "");
        wpm++;
        textBox1.Text = "";
    }
}

所以当我按 Space 而不是textbox1

中写空间时我想要

2 个答案:

答案 0 :(得分:0)

此答案改编自MSDN示例here

// Boolean flag used to determine when a character other than a space is entered
private bool spaceEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    spaceEntered = e.KeyCode == Keys.Space;
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (spaceEntered == true)
    {
        // Stop the character from being entered into the control since 
        e.Handled = true;
    }
}

答案 1 :(得分:-1)

假设您使用的是Windows窗体,则可以使用Handled property of the event覆盖任何关键行为。