【Winform学习笔记(二)】TextBox文本框实现按回车键触发Button事件

TextBox文本框实现按回车键触发Button事件

前言

在本文中主要介绍 如何基于 Winform 框架实现 TextBox 文本框实现按回车键触发 Button 事件,该功能可实现在文本框中输入密码后不需要按登录或确定按钮,直接回车键触发 Button 事件。

正文

1、实现方法

  1. 创建 TextBox 文本框;
  2. 创建 Button 按键;
  3. 增加 TextBox 文本框 的 KeyDown 事件;
  4. 判断键盘按下的是否是回车键,如果是,则调用 Button 的点击事件。

2、具体代码

  1. 创建如下的文本框及按键:
    在这里插入图片描述

  2. 增加 TextBox 文本框 的 KeyDown 事件

            private void txt_KeyDown(object sender, KeyEventArgs e)
            {
          
          
                // 判断:如果输入的是回车键
                if (e.KeyCode == Keys.Enter)
                {
          
          
                    // 触发btn的事件
                    this.btn_Click(sender, e);
                }
            }
    

    在这里插入图片描述

  3. 增加 Button 的Click事件

 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、实现效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/sallyyellow/article/details/130365212