按下按钮后如何将焦点设置回窗体
How to set focus back to form, after button is pressed
我在做游戏,要打开和关闭商店,请按 S。在商店中,您有六个不同的选择可供购买,但它们都是按钮。
但是,一旦你买了东西,焦点就不再在表单上,而是在按钮上,而按键事件是表单的一部分,因此,因为焦点从表单切换到了按钮,按键事件不再有效,并使您无法关闭商店并继续游戏。
我的问题是如何在按下按钮后将焦点设置回表单?我从 Visual Basic 开始,代码类似于 form1.setfocus
,但在 C# 中完全不同。
我已经多次尝试激活表单,.focus
,但似乎没有任何东西可以将焦点设置回表单。将不胜感激。
尝试:
form.Focus();
MSDN:
The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.
Form1.focus();
但我认为,要在 Form
本身上获取键盘事件,您需要为 Form
将 KeyPreview
设置为 true
,以便表单先获取键,然后再获取其他控件。
您也可以将按下事件添加到按钮。
我在做游戏,要打开和关闭商店,请按 S。在商店中,您有六个不同的选择可供购买,但它们都是按钮。
但是,一旦你买了东西,焦点就不再在表单上,而是在按钮上,而按键事件是表单的一部分,因此,因为焦点从表单切换到了按钮,按键事件不再有效,并使您无法关闭商店并继续游戏。
我的问题是如何在按下按钮后将焦点设置回表单?我从 Visual Basic 开始,代码类似于 form1.setfocus
,但在 C# 中完全不同。
我已经多次尝试激活表单,.focus
,但似乎没有任何东西可以将焦点设置回表单。将不胜感激。
尝试:
form.Focus();
MSDN:
The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.
Form1.focus();
但我认为,要在 Form
本身上获取键盘事件,您需要为 Form
将 KeyPreview
设置为 true
,以便表单先获取键,然后再获取其他控件。
您也可以将按下事件添加到按钮。