Cancel PreviewKeyDown

When the input cursor is in the text box, I want to catch the arrow keys, do some processing, and then don't let this event handle the input.

In an KeyPressevent KeyPressEventArgswe can put e.Handled=false; to deal with. But the Arrows keys do not fire the event KeyPress.

I tried with e.IsInputKey = true;, then int KeyDownEvent, as MS says.

Msdn Control.PreviewKeyDown Event

But it e.Handled=false;doesn't seem to work either.

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

enter image description here

I want to change the default keystroke behavior in a TextBox that moves the cursor. I do not want the input cursor between "r" and "l" (see above) to be able to move.

Any suggestion?

+1
1

, , -. , TextBox . . PreviewKeyDown, /. KeyDown.

, , :

    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, , .

+1

Source: https://habr.com/ru/post/1629374/


All Articles