[Winform Study Notes (2)] TextBox text box realizes pressing the Enter key to trigger the Button event

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

  1. Create a TextBox text box;
  2. Create Button button;
  3. Add the KeyDown event of the TextBox text box;
  4. Determine whether the Enter key is pressed on the keyboard. If so, call the Button's click event.

2. Specific code

  1. Create the following text box and button:
    Insert image description here

  2. 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);
                }
            }
    

    Insert image description here

  3. 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();
        }

3. Realize the effect

Insert image description here

Guess you like

Origin blog.csdn.net/sallyyellow/article/details/130365212