Download AltTab.zip We have taken it for granted that TAB and SHIFT + TAB move the focus from one control to the next depending on the TAB order, and rarely wonder how we would implement such functionalities ourselves. Recently, I was asked to implement the same functionality but using different keys (e.g. "+" key TAB forward, "-" key TAB backward). The implementation turns out to be quite simple. The following lines implement such functionalities mentioned above: // The focusedControl holds the control in focus in the current // control collections. private Control focusedControl = null; // This recursive call finds the control that has the focus. // Note: the recursion is necessary since the controls on the private void GetFocusedControl(Control control) { if (control.Focused) { focusedControl = control; } else { foreach (Control c in control.Controls) { GetFocusedControl(c); } } } //Process key strokes protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { focusedControl = null; GetFocusedControl(this); //plus key if ((keyData == Keys.Oemplus) || (keyData == Keys.Add)) { SelectNextControl(focusedControl, true, true, true, true); return true; } //minus key else if ((keyData ==Keys.OemMinus) || (keyData == Keys.Subtract)) { SelectNextControl(focusedControl, false, true, true, true); return true; } return base.ProcessCmdKey (ref msg, keyData); } As can be seen, the key is to find out the control that currently has focus. The controls on a Windows Form form a tree structure, with container controls (e.g. Panels, GroupBoxes) as the root and the controls they contain as leaves. The key step is the function GetFocusedControl. This function iterates trough all the controls in the "tree" and finds out the one that currently has focus. And the reset steps are simple. The overridden method ProcessCmdKey intercepts all key strokes on a form and SelectNextControl is used to select the next control (determined by TAB order) that would receive focus according to the control that currently has the focus. Try out the enclosed sample application to see how it works.

Be Sociable, Share!