检测 KeyUp 事件中的按键

发布于 2024-11-06 06:31:12 字数 956 浏览 1 评论 0原文

我在表单上有一个文本框,我试图检测用户输入的键。文本框是多行的,并且自动换行。我不希望用户按 Enter 键(因为我希望所有文本都在一行中输入,换行),所以我使用了以下代码:

private void txtPlain_KeyPress(object sender, KeyPressEventArgs e) {
    if (e.KeyChar == (char)13) {
        MessageBox.Show("Enter keys are not allowed");
        e.KeyChar = (char)0;
    }
}

这在我的测试中工作正常,但是当我测试 CTRL+ENTER 时,它没有不起作用,因为我不确定如何检测控制键。从我的谷歌搜索中,我发现我需要使用 KeyUp/Down 事件,所以我现在有以下代码:

private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
    //if (e.KeyData == (Keys.Control | Keys.Enter)) {

    if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {            
        MessageBox.Show("Enter keys are not allowed:");
        //e.KeyValue = Keys.None;
    }
}

第一个注释掉的行由于某种原因不起作用,所以如果有人可以解释为什么这会很有用。

KeyUp/Down 事件的问题是我不知道如何从文本中删除 Enter 键 - 与 KeyPress 事件不同,我可以将 KeyChar 设置为零。该事件捕获 Enter 和 Ctrl+Enter 键,但光标仍转到 TextBox 中的下一行。

感谢您对此的任何帮助。

I have a textbox on a form where I'm trying to detect the keys the user types in. The TextBox is multilined with wordwrap on. I don't want the user the press the enter key (as I want all text entered on ONE line, wrapped) so I used the following code:

private void txtPlain_KeyPress(object sender, KeyPressEventArgs e) {
    if (e.KeyChar == (char)13) {
        MessageBox.Show("Enter keys are not allowed");
        e.KeyChar = (char)0;
    }
}

This worked fine in my tests, but when I tested for CTRL+ENTER it didn't work as I'm not sure how to detect for the control key. From my googling I found that I need to use the KeyUp/Down events so I now have the following Code:

private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
    //if (e.KeyData == (Keys.Control | Keys.Enter)) {

    if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {            
        MessageBox.Show("Enter keys are not allowed:");
        //e.KeyValue = Keys.None;
    }
}

The first commented out line didn't work for some reason so if anyone could explain why this would be useful.

The problem with the KeyUp/Down event is that I don't know how to REMOVE the enter key from the text - unlike the KeyPress event when I can set the KeyChar to zero. The event captures both the Enter and Ctrl+Enter keys, but the cursor still goes to the next line in the TextBox.

Thanks for any help on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

醉态萌生 2024-11-13 06:31:13
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
    //if (e.KeyData == (Keys.Control | Keys.Enter)) {

    if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {            
        MessageBox.Show("Enter keys are not allowed:");
        //e.KeyValue = Keys.None;
        // mark event as handled
        e.Handled = true;
    }
} 

来自msdn链接

编辑:

我认为您需要按下按键事件而不是按下按键

EDIT2
这是一些经过测试的代码,它可以按照您的要求工作:

        bool invalid=false;
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode & Keys.Enter) == Keys.Enter)
            {
                invalid = true;
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (invalid)
            {
                e.Handled = true;
            }
            invalid = false;
        }
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
    //if (e.KeyData == (Keys.Control | Keys.Enter)) {

    if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {            
        MessageBox.Show("Enter keys are not allowed:");
        //e.KeyValue = Keys.None;
        // mark event as handled
        e.Handled = true;
    }
} 

from msdnlink

edit:

I think that you need the key down event not the key up

EDIT2
here is some tested code and it works as you wanted:

        bool invalid=false;
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode & Keys.Enter) == Keys.Enter)
            {
                invalid = true;
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (invalid)
            {
                e.Handled = true;
            }
            invalid = false;
        }
快乐很简单 2024-11-13 06:31:13

第一行注释掉的行由于某种原因不起作用,所以如果有人可以解释为什么这会很有用。

您想要检测 Ctrl + Enter。
if (e.KeyData == (Keys.Control | Keys.Enter)) {..

Keys.Control 和 Key.Enter 只不过是一些值 请参考 。现在执行逻辑或不一定会导致已按下的键。完全不合逻辑的条款。

好的,现在来解决您的实际问题,您想要检测 Enter 笔划和 Ctrl + Enter 笔划是否被视为相同。
此外,您想撤消引入的换行符。尝试

使用以下条件的 PreviewKeyDown 或 Preview key up 事件处理程序

if(e.KeyCode==Keys.Enter)

让我知道这是否有效

The first commented out line didn't work for some reason so if anyone could explain why this would be useful.

You wanted to detect Ctrl + Enter.
if (e.KeyData == (Keys.Control | Keys.Enter)) {..

Keys.Control and Key.Enter are nothing but are some values please refer . Now doing logical or will not necessarily result to key which has been pressed. Totally illogical clause.

Ok now come to your actual problem you want to detect Enter stroke and Ctrl + Enter stroke to be treated as same.
Besides you want to undo the newline character thats been introduced. Try

PreviewKeyDown or Preview key up eventhandler with the following condition

if(e.KeyCode==Keys.Enter)

Let me know if this works

风筝有风,海豚有海 2024-11-13 06:31:12

嗯,没有理由通过处理 KeyDownKeyUp 事件来禁止使用 Enter 键。您只需设置 AcceptsReturn<将文本框控件的 /code> 属性设置为 False。这将阻止多行文本框响应 Enter 键的按下。

当然,这并不能解决Ctrl+Enter的问题。事实上,当 AcceptsReturn 属性设置为 False 时,这是创建新行的预期方式。为了解决这个问题,您需要处理一个键盘事件并阻止控件接收此输入。

KeyDown 是一个很好的起点。您想要做的是过滤掉包含 Keys.Enter 标志的任何键盘事件。无论它们与哪个其他修饰键组合,这都会捕获它们。然后,一旦找到 Enter 按键,您需要将 e.Handled 属性设置为 True,以防止它传递到控件。

但不幸的是,我们还没有完全完成。文本框控件尝试在内部处理某些键,并且您将无法在键事件处理程序方法中覆盖它。您还需要告诉控件不要将该特定键解释为输入键。有两种主要方法可以做到这一点。第一种(也是推荐的方法)是从基 TextBox 类继承来创建您自己的自定义控件,然后覆盖受保护的 IsInputKey 方法。第二种(稍微简单一些)方法只是处理 PreviewKeyDown 事件,并将 IsInputKey 属性设置为 False。

示例代码:

private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    // Check if the KeyCode value has the Keys.Enter flag set
    if ((e.KeyCode & Keys.Enter) == Keys.Enter)
    {
        // Set the IsInputKey property to False
        e.IsInputKey = false;
    }
}

private void txtPlain_KeyDown(object sender, KeyEventArgs e)
{
    // Check if the KeyCode value has the Keys.Enter flag set
    if ((e.KeyCode & Keys.Enter) == Keys.Enter)
    {            
        // Show the user a message
        MessageBox.Show("Enter keys are not allowed in this textbox.");

        // Prevent the key event from being passed on to the control
        e.Handled = true;
    }
}

虽然我认为这仅用于测试目的,但您肯定希望将 MessageBox 调用从那里取出以用于生产代码。找到另一种方式来警告用户不允许其输入,例如短促的蜂鸣声和 ErrorProvider 组件 放置在文本框旁边。显示消息框非常不和谐,而且不太用户友好。请参阅我的答案 获取其他提示和技巧。

Hmm, there's no reason to disallow the Enter key by handling the KeyDown or KeyUp events. You can simply set the AcceptsReturn property of the textbox control to False. This will prevent a multiline textbox from responding to a press of the Enter key.

Of course, this doesn't solve the problem of Ctrl+Enter. In fact, that's the expected way to create a new line when the AcceptsReturn property is set to False. To solve that, you will need to handle one of the keyboard events and prevent the control from receiving this input.

KeyDown is a good place to start. What you want to do is filter out any keyboard events that include the Keys.Enter flag. That will catch them no matter which other modifier key they might be combined with. Then, once you've found an Enter keypress, you want to set the e.Handled property to True in order to prevent it from being passed on to the control.

But unfortunately, we're not quite done yet. The textbox control tries to handle certain keys internally, and you're not going to be able to override that in a key event handler method. You also need to tell the control not to interpret that particular key as an input key. There are two primary ways of doing this. The first (and recommended way) is to inherit from the base TextBox class to create your own custom control, and then override the protected IsInputKey method. The second (somewhat simpler) way is just to handle the PreviewKeyDown event, and set the IsInputKey property to False.

Sample code:

private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    // Check if the KeyCode value has the Keys.Enter flag set
    if ((e.KeyCode & Keys.Enter) == Keys.Enter)
    {
        // Set the IsInputKey property to False
        e.IsInputKey = false;
    }
}

private void txtPlain_KeyDown(object sender, KeyEventArgs e)
{
    // Check if the KeyCode value has the Keys.Enter flag set
    if ((e.KeyCode & Keys.Enter) == Keys.Enter)
    {            
        // Show the user a message
        MessageBox.Show("Enter keys are not allowed in this textbox.");

        // Prevent the key event from being passed on to the control
        e.Handled = true;
    }
}

And, though I assume this is for testing purposes only, you definitely want to take that MessageBox call out of there for production code. Find another way to alert the user that their input was not allowed, such as a short beep sound and an ErrorProvider component placed next to the textbox. Showing a message box is very jarring, and not very user-friendly. See my answer here for other hints and tips.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文