【发布时间】:2012-08-10 14:36:21
【问题描述】:
VS2010 C# .Net 4.1
我正在处理一个表单,用户必须在ComboBox 中选择或输入初始数据。使用下面的代码,这需要一些时间来推断,如果数据正确,当用户点击Tab 键时,我启用编辑按钮,否则按钮被禁用,它会移动到下一个按钮。
此代码有效,但副作用是当我将IsInputKey 设置为true 时PreviewKeyDown 事件再次发生。这会调用两次验证。 KeyDown 事件只被调用一次,IsInputKey 在第二次调用时再次为假,所以我需要再次检查验证。
我想了解原因并可能避免它。
private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
if (e.KeyData == Keys.Tab) {
if (ValidationRoutine()) {
e.IsInputKey = true; //If Validated, signals KeyDown to examine this key
} //Side effect - This event is called twice when IsInputKey is set to true
}
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.Tab) {
e.SuppressKeyPress = true; //Stops further processing of the TAB key
btnEdit.Enabled = true;
btnEdit.Focus();
}
}
【问题讨论】:
-
您是否尝试过删除 PreviewKeyDown 中的代码并将代码添加到不同的事件处理程序中。PreviewKeyDown 在实际 KeyDown 事件之前发生/被触发。
-
@DJ KRAZE-这是允许在 KeyDown 事件中抑制 Tab 的必要条件。如果我不按下它,焦点将移至顺序中的下一个按钮,因为我的目标按钮没有及时启用。我可以在其他地方进行全面验证,并为这个测试检查一个简单的标志。但我想知道为什么它被调用了两次。