[英]Focus changes even after setting e.Handled = true
I've set KeyPreview = true;
我将
KeyPreview = true;
设置KeyPreview = true;
for my Form
. 为我的
Form
。 I basically want to use the arrow keys to go to the next and previous images instead of changing focus to different controls. 我基本上想使用箭头键转到下一个和上一个图像,而不是将焦点更改为其他控件。 I've set the
Handled
property to true
but still the focus changes on arrow key press. 我已将
Handled
属性设置为true
但是焦点仍然在箭头键按下时更改。
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
// Do stuff
}
else if (e.KeyCode == Keys.Left)
{
// Do stuff
e.Handled = true;
}
else if (e.KeyCode == Keys.Right)
{
// Do stuff
e.Handled = true;
}
}
EDIT 编辑
The behavior I want to achieve is as follows. 我要实现的行为如下。
Left Arrow Key -> Previous Image
Right Arrow Key -> Next Image
Now, I also have a few TextBox
es on my Form
and I therefore do not want to go to next and previous images if those Textbox
es are in focus because then it should navigate through the text instead. 现在,我的
Form
上还有一些TextBox
,因此如果这些Textbox
处于焦点,我就不想转到下一张和上一张图像,因为那样的话,它应该在文本中导航。
This worked for me. 这对我有用。
KeyPreview = true;
KeyPreview = true;
设置KeyPreview = true;
for the Form
. Form
。 Override ProcessCmdKey
and process as needed if any of the TextBox
es do not have focus. 如果任何
TextBox
没有焦点,则覆盖ProcessCmdKey
并根据需要进行处理。
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (textBox1.ContainsFocus || textBox2.ContainsFocus || textBox3.ContainsFocus) { return base.ProcessCmdKey(ref msg, keyData); } if (keyData == Keys.Delete) { removeRect(); return true; } else if (keyData == Keys.Left) { previousImg(); return true; } else if (keyData == Keys.Right) { nextImg(); return true; } else { return base.ProcessCmdKey(ref msg, keyData); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.