WinForms AcceptButton not working?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 15:34:59
Martin Moser

Just setting the AcceptButton/CancelButton is not enough. This just tells which button should be invoked on Enter/Esc. You have to set the DialogResult in the Button handler.

Samuel

Try setting DialogResult on button1

this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;

I had an issue with the AcceptButton not working and while the DialogResult suggestion was part of the fix, I had 2 other things that needed to change:

  1. My button was not visible - Intentionally because I wanted to stop the "ding" when a carriage return was "pressed" by scanning a barcode.
  2. The container that the button was inside made a difference. I had to have it in the same container, in my case a Forms.Panel, as the textbox that was trying to access it. I'm not sure why this would make a difference, but it did.

I hope this helps someone.

You need to set the KeyPreview property of the form to True, the default value is False. Remember that if focus is set to any other button rather than the AcceptButton the Enter key will execute this button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!