C#之敲击回车键触发Button的Click事件

C#之敲击回车键触发Button的Click事件

在做项目时,需要在TextBox控件中输入指令,点击Button后将指令传给下位机。为了简化操作,想直接敲击回车键实现Button的Click事件来发送指令,通过查阅资料,实现了这一操作,示例代码如下:

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

另外,这里也涉及到在一个控件的事件中执行另一控件的事件。比如,在一个Button2的Click事件中执行Button1的Click事件,也就是说,在单击Button2的同时也单击了Button1,示例代码如下:

        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);
            //也可继续编写后续要执行的代码
            、、、、        
        }

猜你喜欢

转载自blog.csdn.net/Kevin_Sun777/article/details/109124430