我正在开发一个程序,该程序允许用户通过扫描仪输入条形码然后做一些事情,我已经完成了大部分工作,我只是不知道 textBox1 的哪种操作方法可以让我做在文本框中按下“Enter”时的东西。我查看了大多数操作的描述,但我找不到一个听起来可行的。
有没有可以工作的?还是我只需要在每次按下键时检查?
我正在开发一个程序,该程序允许用户通过扫描仪输入条形码然后做一些事情,我已经完成了大部分工作,我只是不知道 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());
}
}