[英]How do I add a keyboard shortcut (enter) to my textbox in C#?
So I'm still very new to programming and I'm trying to create a program in which you'll enter a number (from 1-9 only) in a textbox and then clicking Enter instead of having to click on a button to have the number that I wrote on the textbox displayed on my second label. 因此,我对编程还是很陌生,我正在尝试创建一个程序,在该程序中,您将在文本框中输入数字(仅限1-9),然后单击Enter,而不必单击按钮即可我在第二个标签上显示的在文本框中写的数字。 I keep getting two errors, the first throws off a 我不断收到两个错误,第一个错误
No overload for 'textBox1_TextChanged' matches delegate 'EventHandler'
when I add Key
to EventArgs
(because EventArgs
does not contain Keycode
). 当我将Key
添加到EventArgs
(因为EventArgs
不包含Keycode
)。 The second is flags here: 第二个是这里的标志:
this.label2.Click += new System.EventHandler(this.label2_Click);
"CS1061 'Form1' does not contain a definition for 'label2_Click' and no extension method 'label2_Click' accepting a first argument of type 'Form1' could be found (are you missing a using directive or an assembly reference?)" “ CS1061'Form1'不包含'label2_Click'的定义,并且找不到扩展方法'label2_Click'接受类型为'Form1'的第一个参数(您是否缺少using指令或程序集引用?)”
My code: 我的代码:
using System;
using System.Windows.Forms;
namespace Tarea7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
label2.Text = textBox1.ToString();
}
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Debes de escribir un numero de 1-9");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
private void label2_TextChanged(object sender, EventArgs e)
{
}
}
}
Add textBox1_KeyDown
event to your textBox1.KeyDown
event at visual designer or at the file Form1.designer.cs: 添加textBox1_KeyDown
事件您textBox1.KeyDown
在可视化设计器或文件Form1.designer.cs事件:
this.textBox1.KeyDown +=
new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
Then add following function to your code. 然后将以下函数添加到您的代码中。 When user type a number from 1 - 9 and press Enter, it will be copied to label2
. 当用户键入1到9之间的数字并按Enter时,它将被复制到label2
。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
Text = DateTime.Now.ToString();
switch (e.KeyCode)
{
case Keys.Enter:
if (textBox1.Text.Length == 1)
{
char tbChar = textBox1.Text[0];
if (tbChar >= '1' && tbChar <= '9')
{
MessageBox.Show("Correct");
label2.Text = tbChar.ToString();
// Clear textbox
textBox1.Text = "";
return;
}
}
MessageBox.Show("Your input is not a number from 1 - 9");
break;
}
}
Also, you don't need this line, remove it: 另外,您不需要此行,请将其删除:
this.label2.Click += new System.EventHandler(this.label2_Click);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.