Cancel PreviewKeyDown

[亡魂溺海] 提交于 2020-01-05 02:11:56

问题


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.

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

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

Msdn Control.PreviewKeyDown Event

But seems e.Handled=false; doesn't work neither.

Here is my current code

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;               
     }
}

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.

Any suggestion?


回答1:


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;
        }
    }

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



来源:https://stackoverflow.com/questions/31673415/cancel-previewkeydown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!