Search code examples
c#winformskeydownhotkeyskeypreview

Why does this code only work in one instance?


I've set my form's KeyPreview property to true.

I've added this code:

private void PlatypusScheduleForm_KeyDown(object sender, KeyEventArgs e) 
{
  if (e.KeyCode == Keys.F9)
  {
    tabControlPlatypi.SelectedTab = tabPageDuckBill;
  }
  else if (e.KeyCode == Keys.F10)
  {
    tabControlPlatypi.SelectedTab = tabPagePlatypus;
  }
}

When I mash F10, it works as expected; mashing F9, however, does nothing.

tabPageDuckBill is the design-time/default tabPage that displays. Why would F10 work in taking me to the "other" tab page, but F9 then not go back to the original?


Solution

  • I found that if I just did this:

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.F9)
      {
          tabControl1.SelectedTab = tabPage1;
          e.SuppressKeyPress = true;
      }
      else if (e.KeyCode == Keys.F10)
      {
          tabControl1.SelectedTab = tabPage2;
          e.SuppressKeyPress = true;
      }
    }
    

    it'll toggle back and forth just fine. Without that e.SuppressKeyPress = true;, however, it exhibited the behavior you mentioned.