取消PreviewKeyDown [英] Cancel PreviewKeyDown

查看:297
本文介绍了取消PreviewKeyDown的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当键入光标在文本框中时,我想按箭头键, 做一些处理,然后阻止输入处理此事件.

When the typing cursor is in a textbox I want catch the Arrow keys, do some treatment then prevent this event for being handled by the input.

KeyPress事件中,我们有KeyPressEventArgs可以放入e.Handled=false; 处理. 但是,箭头键不会触发KeyPress事件.

In KeyPress event we have KeyPressEventArgs that we can put e.Handled=false; to deal with. But Arrows keys don't trig KeyPress event.

我已经尝试过使用e.IsInputKey = true;,然后按照MS的说明进行int KeyDown事件.

I have tried with e.IsInputKey = true; then int KeyDown Event as MS says.

但是e.Handled=false;似乎也不起作用.

这是我当前的代码

private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{    
      if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Left)
                e.IsInputKey = true;               
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{                         
     if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Left)
     {
            // some other treatment [...]
        e.Handled = false;               
     }
}

我想更改文本框中移动光标的默认按箭头行为.我不希望在"r"和"l"(上方)之间的键入光标能够移动.

I want to change the default pressing arrow behaviour in TextBox which moves the cursor. I don't want to the typing cursor between "r" and "l" (above) could be able to move.

有什么建议吗?

推荐答案

问题是模糊的,它没有描述需要特定操作的特定光标键.重要的是,TextBox已经将向右和向左光标键转换为输入键.这样它们就不会用于控件之间的导航.如果要拦截上/下光标键,则仅需要PreviewKeyDown.在KeyDown事件处理程序中实现行为.

The question is vague, it doesn't describe the specific cursor keys that need to act differently. It matters, TextBox already turns the Right and Left cursor keys into input keys. So that they won't be used for navigation between controls. You only need PreviewKeyDown if you want to intercept the Up/Down cursor keys. Implement behavior in the KeyDown event handler.

意图也很模糊,我只给出一个非常愚蠢的示例,该示例交换了光标键的方向:

Intention is vague as well, I'll just give a very silly example that swaps the direction of the cursor keys:

    private void textBox1_KeyDown(object sender, KeyEventArgs e) {
        var box = (TextBox)sender;
        if (e.KeyData == Keys.Left) {
            if (box.SelectionStart < box.Text.Length)
                box.SelectionStart++;
            e.Handled = true;
        } else if (e.KeyData == Keys.Right) {
            if (box.SelectionStart > 0)
                box.SelectionStart--;
            e.Handled = true;
        }
    }

请注意,必须将e.Handled设置为 true ,以确保不会将按键传递给控件.

Note how e.Handled must be set to true to ensure that the keystroke isn't passed on to the control.

这篇关于取消PreviewKeyDown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆