编辑:正如 Rob 所说,我再次问了这个问题,这里有新的和正确的标题。
我有一个带有 CancelButton 和 AcceptButton 的表单(名为 btnCancel 和 btnOK)。我有一些组合框作为输入字段。
ComboBoxes 阻止我的 AcceptButton 和 CancelButton 接收 Escape 和 Enter 键,所以我将此代码添加到 KeyDown 事件的所有字段:
if (e.KeyData == Keys.Escape)
{
ComboBox field = (ComboBox)sender;
if ((field.DropDownStyle == ComboBoxStyle.Simple) || (!field.DroppedDown))
{
e.SuppressKeyPress = true;
btnCancel.PerformClick();
}
}
else if (e.KeyData == Keys.Enter)
{
ComboBox field = (ComboBox)sender;
if ((field.DropDownStyle == ComboBoxStyle.Simple) || (!field.DroppedDown))
{
e.SuppressKeyPress = true;
btnOK.PerformClick();
}
}
这是 OK 按钮的 Clicked 事件中的代码:
if (!changesAreSaved)
{
SaveChangesToNode();
}
List<int> invalidIndices = ValidateAndRefineNodes(true);
if (invalidIndices.Count == 0)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
if (nodesToEdit.Count > 1)
{
trvCategories.SelectedNode = trvCategories.Nodes[invalidIndices[0]];
}
FocusOnFirstField(true);
MessageBox.Show(this, "Enter correct values for all fields before you press OK.", "Cannot Save Information",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
一切正常,但 btnOK_Clicked仅在显示其 MessageBox 时才被调用两次。
这是第一次调用的调用堆栈:
这是第二个:
如您所见,第二次呼叫根本不应该发生。在第二个调用堆栈中,第一个 btnOK_Click (第三行)再次从 MessageBox.Show(...) 调用 Fields_KeyDown (第二行)。这怎么可能?我很困惑...
编辑:当我单击确定按钮时,一切正常。仅当我在键盘上按 Enter 时才会出现此问题。