Why does this code only work in one instance?

235 views Asked by At

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?

2

There are 2 answers

0
itsmatt On BEST ANSWER

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.

0
Sam Anwar On

I ran into this same problem in the past, and the problem persisted even after removing suspect code from the SelectedIndexChanged() event. I then used a different techniques that worked much better. Instead of using the form KeyDown event, I overrode the form ProcessCmdKey event as follow:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
  if (keyData == Keys.F9)
  {
    this.tabControl1.SelectedTab = tabPage1;
    return true;    
  }
  else if (keyData == Keys.F10)
  {
    this.tabControl1.SelectedTab = tabPage2;
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}