1

我有一个 MDI windows 窗体应用程序,我的子窗体大多有“确定”和“取消”按钮。但是,我不希望使用 ENTER/ESC 键激活它们以防止意外保存/中止。因此,表单将 AcceptButton 和 CancelButton 都设置为 none。ESC 按钮确实什么都不做,但 ENTER 按钮仍然通过“单击”找到的第一个按钮关闭表单,按 TabOrder 排序。

为什么会这样?我真的必须开始做变通方法并抓住 ENTER 键吗?

补充:好的,这更奇怪。Reflector 告诉我,如果 Tab Order 的第一个控件(实际上是打开表单时默认处于活动状态的控件)是一个按钮,那么它将被分配为默认控件。否则什么都不会发生。现在问题变为:WTF?!

4

3 回答 3

1

当您将 AcceptButton/CancelButton 属性设置为 None 时,所有设计器都将 DialogResult 属性设置为您的按钮,并且不要清除它们。因此,您必须手动完成(在您的代码或设计器中)。

Button okButton = new Button();

// some code here

okButton.DialogResult = DialogResult.None;
于 2013-09-10T12:56:01.673 回答
0

I was just stuck on the same problem. Was not using WinForms for a long time, thought can I be missing something in such simple thing?

In my case, I want "Ok" button to be invisible (or disabled) while some task runs, and then appear in the end... So at the start, only "Cancel" is shown, and it's always the "accept"! No matter if I set AcceptButton to "Ok", or to "None", and after the "Ok" appears on form - still "Cancel" acts on Enter. If both buttons are always visible and enabled - it's correct. Well... I thought it was correct, but now after reading this, I tried switching buttons order and yes, it's the first button that is always "accept".

It appears that Form.AcceptButton is just obsolete and unused now. Form.CancelButton is working still, though. I know this is the way how it works in HTML, but in WinForms... I have the same "wtf" question. .NET 4.5.

于 2015-03-25T17:45:25.103 回答
0

听起来,由于 OK 按钮是 tab 顺序中的第一个控件,因此在加载表单时它会自动获得键盘焦点,这意味着按 enter 将单击它。如果您希望键盘焦点转到另一个控件,请尝试将 ActiveControl 属性设置为论坛上的另一个元素。

Button okButton = new Button();
TextBox someOtherControl = new TextBox();

// Add controls to form.
this.Controls.Add(okButton);
this.Controls.Add(someOtherControl);

// Specifically set the ActiveControl on the form.
this.ActiveControl = someOtherControl;
于 2010-03-23T13:49:27.447 回答