【发布时间】:2009-08-04 10:21:39
【问题描述】:
当组合框处于活动状态时,如何在 Windows 窗体组合框中捕获回车键?
我尝试听 KeyDown 和 KeyPress,并创建了一个子类并重写了 ProcessDialogKey,但似乎没有任何效果。
有什么想法吗?
/P
【问题讨论】:
-
你定义了 AcceptButton 吗?
标签: c# windows winforms combobox
当组合框处于活动状态时,如何在 Windows 窗体组合框中捕获回车键?
我尝试听 KeyDown 和 KeyPress,并创建了一个子类并重写了 ProcessDialogKey,但似乎没有任何效果。
有什么想法吗?
/P
【问题讨论】:
标签: c# windows winforms combobox
将 KeyPress 事件连接到这样的方法:
protected void myCombo_OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
MessageBox.Show("Enter pressed", "Attention");
}
}
我已经在带有 VS2008 的 WinForms 应用程序中对此进行了测试,并且可以正常工作。
如果它不适合您,请发布您的代码。
【讨论】:
如果您在表单上定义 AcceptButton,则无法在 KeyDown/KeyUp/KeyPress 中收听 Enter 键。
为了检查这一点,您需要覆盖 FORM 上的 ProcessCmdKey:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if ((this.ActiveControl == myComboBox) && (keyData == Keys.Return)) {
MessageBox.Show("Combo Enter");
return true;
} else {
return base.ProcessCmdKey(ref msg, keyData);
}
}
在此示例中,如果您在组合框上,它将为您提供消息框,并且它对所有其他控件的工作方式与以前一样。
【讨论】:
或者您也可以连接 KeyDown 事件:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter pressed.");
}
}
【讨论】:
private void comboBox1_KeyDown( object sender, EventArgs e )
{
if( e.KeyCode == Keys.Enter )
{
// Do something here...
} else Application.DoEvents();
}
【讨论】:
试试这个:
protected override bool ProcessCmdKey(ref Message msg, Keys k)
{
if (k == Keys.Enter || k == Keys.Return)
{
this.Text = null;
return true;
}
return base.ProcessCmdKey(ref msg, k);
}
【讨论】:
可能是您的对话框有一个按钮正在吃回车键,因为它被设置为表单属性中的 AcceptButton。
如果是这种情况,那么您可以通过在控件获得焦点时取消设置 AcceptButton 属性然后在控件失去焦点时将其重置(在我的代码中,button1 是接受按钮)来解决这个问题
private void comboBox1_Enter(object sender, EventArgs e)
{
this.AcceptButton = null;
}
private void comboBox1_Leave(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
MessageBox.Show("Hello");
}
}
我不得不承认我不喜欢我自己的解决方案,因为取消设置/设置 AcceptButton 属性似乎有点笨拙,所以如果有人有更好的解决方案,那么我会感兴趣
【讨论】:
protected void Form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13) // or Key.Enter or Key.Return
{
MessageBox.Show("Enter pressed", "KeyPress Event");
}
}
不要忘记在表单上将 KeyPreview 设置为 true。
【讨论】: