简体   繁体   中英

Focus changes even after setting e.Handled = true

I've set KeyPreview = true; for my 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.

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.

This worked for me.

  1. Do not set KeyPreview = true; for the Form .
  2. Override ProcessCmdKey and process as needed if any of the TextBox es do not have focus.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM