C# hits the Enter key to trigger the Click event of the Button

C# hits the Enter key to trigger the Click event of the Button

When working on a project, you need to input instructions in the TextBox control, and then click the Button to send the instructions to the lower computer. In order to simplify the operation, I want to directly hit the Enter key to realize the Click event of the Button to send the command. This operation is realized by looking up the information. The sample code is as follows:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                button1.Focus();
                button1_Click(this, new EventArgs());
            }
        }

In addition, it also involves executing the event of another control in the event of one control . For example, the Click event of Button1 is executed in the Click event of Button2, that is, when Button2 is clicked, Button1 is also clicked. The sample code is as follows:

        private void button1_Click(object sender, EventArgs e)
        {
            //在此编写要在button1的Click事件中执行的代码
            、、、、
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //在button2的Click事件中执行button1的Click事件
            button1_Click(sender, e);
            //也可继续编写后续要执行的代码
            、、、、        
        }

 

Guess you like

Origin blog.csdn.net/Kevin_Sun777/article/details/109124430