文本框操作方法

本文关键字:操作方法 文本 | 更新日期: 2023-09-27 18:35:45

我正在开发一个允许用户通过扫描仪输入条形码然后做事的程序,我已经解决了大部分问题,我只是无法弄清楚 textBox1 的哪种操作方法允许我在文本框中点击"Enter"时做某事。我查看了大多数操作的描述,但我找不到听起来可行的操作。

有没有一个会起作用?还是我只需要在每次按下键时检查?

文本框操作方法

你想要KeyDown/OnKeyDown或KeyUp/OnKeyUp事件,只需过滤正确的键:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.KeyCode == Keys.Enter)
    {
        // Do Something
    }
}

或者,在您的情况下,由于父窗体很可能订阅 TextBox 事件,因此您将使用设计器添加如下所示的方法:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        // Do Something
    }
}

请记住,您所谓的"操作方法"称为事件。

试试这个,使用 KeyUp 事件:

    private void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            DoSomething();
        }
    }

尝试处理程序按键事件。停止处理程序并更好地工作。

 using System;
 using System.Windows.Forms;
public class Form1: Form
{
public Form1()
{
    // Create a TextBox control.
    TextBox tb = new TextBox();
    this.Controls.Add(tb);
    tb.KeyPress += new KeyPressEventHandler(keypressed);
}
private void keypressed(Object o, KeyPressEventArgs e)
{
    // The keypressed method uses the KeyChar property to check  
    // whether the ENTER key is pressed.  
    // If the ENTER key is pressed, the Handled property is set to true,  
    // to indicate the event is handled. 
    if (e.KeyChar != (char)Keys.Enter)
    {
        e.Handled = true;
    }
}
public static void Main()
{
    Application.Run(new Form1());
}

}