TextBox text box implements pressing the Enter key to trigger the Button event
Preface
This article mainly introduces how to implement the TextBox text box based on the Winform framework to trigger the Button event by pressing the Enter key. This function allows you to directly trigger the Button event by pressing the Enter key without pressing the login or OK button after entering the password in the text box.
text
1. Implementation method
- Create a TextBox text box;
- Create Button button;
- Add the KeyDown event of the TextBox text box;
- Determine whether the Enter key is pressed on the keyboard. If so, call the Button's click event.
2. Specific code
-
Create the following text box and button:
-
Add the KeyDown event of the TextBox text box
private void txt_KeyDown(object sender, KeyEventArgs e) { // 判断:如果输入的是回车键 if (e.KeyCode == Keys.Enter) { // 触发btn的事件 this.btn_Click(sender, e); } }
-
Add Button's Click event
public class Course
{
//共有的成员变量(存储数据或对外提供数据)
public int CourseId;
public string CourseName;
private readonly int UnitPrice = 100;
public DateTime FirstTime;
//共有方法
public string ShowCourseInfo()
{
//局部变量
string info = $"名称:{
CourseName},编号:{
CourseId},价格:{
UnitPrice}";
return info;
}
}
private void btn_Click(object sender, EventArgs e)
{
btn.Width = 223;
Course course = new Course
{
CourseName = "C#",
CourseId = 1001
};
btn.Text = course.ShowCourseInfo();
}