捕获并处理 KeyPress/KeyDown 而不修改 TextBox 中的文本
Catch and process KeyPress/KeyDown without modifying text in TextBox
我目前有以下事件处理程序,它在我的表单代码中捕获 Ctrl+Enter 组合键:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
}
}
我在表单中还有两个非只读文本框,其中一个是多行的,而另一个不是。每当我按 Ctrl+Enter 键时,事件都会得到处理,但当焦点位于任一 TextBox 中时,它也会注册为 Enter 按键。我想要做的是注册组合键 而没有 Enter 按键修改任一框中的文本。我有什么办法可以做到这一点吗?
您应该相应地使用 PreviewKeyDown
event instead and set the IsInputKey
属性:
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
e.IsInputKey = false;
}
}
UPDATE:从您的处理程序名称来看,我猜您已将其添加到 Form
的 KeyPress/KeyDown/PreviewKeyDown
事件中。相反,您应该在每个 TextBox
的 PreviewKeyDown
事件中注册我上面显示的方法。
为了不破坏已经为你工作的东西,你可以保留你的代码,只需在你设置 IsInputKey
的 TextBox
的 PreviewKeyDown
事件中添加一个处理程序对于指定的键为假,但不要做你的 // Stuff
.
您最好的选择是使用 ProcessCmdKey
:只需将其添加到您的表单中即可:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.Enter))
{
// Stuff
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
我目前有以下事件处理程序,它在我的表单代码中捕获 Ctrl+Enter 组合键:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
}
}
我在表单中还有两个非只读文本框,其中一个是多行的,而另一个不是。每当我按 Ctrl+Enter 键时,事件都会得到处理,但当焦点位于任一 TextBox 中时,它也会注册为 Enter 按键。我想要做的是注册组合键 而没有 Enter 按键修改任一框中的文本。我有什么办法可以做到这一点吗?
您应该相应地使用 PreviewKeyDown
event instead and set the IsInputKey
属性:
private void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter && e.Control)
{
// Stuff
e.IsInputKey = false;
}
}
UPDATE:从您的处理程序名称来看,我猜您已将其添加到 Form
的 KeyPress/KeyDown/PreviewKeyDown
事件中。相反,您应该在每个 TextBox
的 PreviewKeyDown
事件中注册我上面显示的方法。
为了不破坏已经为你工作的东西,你可以保留你的代码,只需在你设置 IsInputKey
的 TextBox
的 PreviewKeyDown
事件中添加一个处理程序对于指定的键为假,但不要做你的 // Stuff
.
您最好的选择是使用 ProcessCmdKey
:只需将其添加到您的表单中即可:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.Enter))
{
// Stuff
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}