C # Winfrom program in the ENTER key associated button button

Source: Internet
Author: User

1,关联按钮上的Key事件      在按钮上的keypress,keydown,keyup事件必须要获得焦点,键盘上的键才能有效。     privatevoidbtnEnter_KeyDown(objectsender, KeyEventArgs e)        {                      if(e.KeyCode == Keys.Enter)//如果输入的是回车键            {                this.btnEnter_Click(sender, e);//触发button事件            }        }   只有btnEnter获得焦点后,回车才有效。//PS:貌似按钮获得焦点后,会自己响应回车    2,窗体上的Key事件  privatevoidfrm_test_KeyPress(objectsender, KeyPressEventArgs e)        {            if ((Keys)e.KeyChar == Keys.Escape) {                buttonESC_Click(sender,e);            }        }这个时候发现,按键盘上的Esc键还是没有反应。 还需要在窗体上注册控件的键盘事件,把窗体的KeyPreview属性设置成 true    3,还有一种更简单的方法。网上搜的,还没有测试,不知道是否可行。       Winform中的按钮要响应回车事件,是很简单的事情!只要设置窗体中的属性设置一下就可以了! 比如有登录窗体(Form_Login),包含有两个按钮登录 (btnLogin)和退出(btnExit),想要登录 (btnLogin)响应回车键,则设置窗体(Form_Login)的属性AcceptButton为btnLogin即可!即Form_Login.AcceptButton=btnLogin; 同样道理,设置窗体(Form_Login)的属性CancelButton为btnExit,就可以响应Esc键了!即Form_Login.CancelButton=btnExit;很简单! 如果还是不明白应该加在什么地方,我就举例说明一下:         privatevoidForm3_Load(objectsender, EventArgs e)        {            Form_Login.AcceptButton = btnLogin;//btnLogin是登陆按钮            Form_Login.CancelButton = btnExit;//btnExit是退出按钮        }

Http://www.cnblogs.com/xiaofengfeng/archive/2011/09/16/2178655.html

C # Winfrom program in the ENTER key associated button button

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.