问题
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