22 December 2012

Control focus with Arrow key in Windows forms

When working on Win forms application, often it’s a requirement to change the control focus using the up and down arrow keys. By default on windows forms (when building on Microsoft .NET) the control focus can be changed only using the TAB (puts focus to next control) and Shift+TAB(puts focus to previous control) keys.

If you want to achieve focus change with the Arrow keys you need to override ProcessCmdKey() method like below.

protected override bool ProcessCmdKey
            (ref Message msg, Keys keyData)
 {
  switch (keyData)
  {
    case Keys.Up:
    case Keys.Down:

    bool forward = (keyData == Keys.Down);
    if (this.ProcessTabKey(forward))
       {
          return true;
       }

    break;
  }
  return base.ProcessCmdKey(ref msg, keyData);
 }
By overriding the ProcessCmdKey() in the windows form, we can achieve the below.
  1. Putting the focus to next control with the down arrow key.
  2. Put the focus to next control with the up arrow key.

You can create a CustomForm and override the ProcessCmdKey() method and add the above implementation. In which form you want to change the tab focus with arrow keys you can derive that form from the CustomForm created.

For some reason if you don’t want this behaviour for some controls on the windows forms, you can exclude them like below.

protected override bool ProcessCmdKey
               (ref Message msg, Keys keyData)
 {
    // Add controls for which Arrow keys => 
    // focus is not required.
    if (!(ActiveControl is ListView || ActiveControl is ComboBox 
       || ActiveControl is TreeView))
      {
        switch (keyData)
         {
            case Keys.Up:
            case Keys.Down:

            bool forward = (keyData == Keys.Down);
            if (this.ProcessTabKey(forward))
            {
              return true;
            }
            break;
          }
       }
    return base.ProcessCmdKey(ref msg, keyData);
 }
Documentation on MSDN: Form.ProcessCmdKey Method

No comments:

Post a Comment