views:

693

answers:

2

Hi! Iam facing such problem, which I find hard to overcome. In WinForms I got a TabControl with n TabPages. I want to extend the Ctrl+Tab / Ctrl+Shift+Tab switching. so I wrote some code which works fine as long as the focus is on TabControl or on the Form. When application focus is INSIDE of TabPage (for example on a button which is placed inside of TabPage), while pressing Ctrl+Tab, my code is ignored and TabControl skips to TabPage on his own (avoiding my code).

Anyone idea ?

+1  A: 

You need to derive from TabControl and override ProcessCmdKey, virtual method in order to override the Ctrl-Tab behavior.

Example:

public class ExtendedTabControl: TabControl
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.Tab))
        {
            // Write custom logic here
            return true;
        }
        if (keyData == (Keys.Control | Keys.Shift | Keys.Tab))
        {
            // Write custom logic here, for backward switching
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}
Pop Catalin
+1  A: 

TabControl has fairly unusual processing to handle the Tab key. It overrides the ProcessKeyPreview() method to detect Ctrl/Shift/Tab, then implements the tab selection in its OnKeyDown() method. It does this so it can detect the keystroke both when it has the focus itself as well as any child control. And to avoid stepping on custom Tab key processing by one of its child controls. You can make it work by overriding ProcessCmdKey() but then you'll break child controls that want to respond to tabs.

Best thing to do is to override its OnKeyDown() method. Add a new class to your project and paste the code shown below. Compile. Drop the new tab control from the top of the toolbox onto your form.

using System;
using System.Windows.Forms;

class MyTabControl : TabControl {
  protected override void OnKeyDown(KeyEventArgs e) {
    if (e.KeyCode == Keys.Tab && (e.KeyData & Keys.Control) != Keys.None) {
      bool forward = (e.KeyData & Keys.Shift) == Keys.None;
      // Do your stuff
      //...
    }
    else base.OnKeyDown(e);
  }
}

Beware that you also ought to consider Ctrl+PageUp and Ctrl+PageDown.

Hans Passant