0

I am trying to make a set of nine check boxes that correspond to the number pad, so for example, hitting the "7" key on the number pad would make the top left check box check or uncheck accordingly.

What I am unable to determine is how to make the KeyDown be represented so that the items can be selected regardless of whatever is currently focused on the page, and also how to point the KeyDown to the corresponding check box to make it switch from being checked or unchecked. Thank you for your input.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
Tim
  • 23
  • 1
  • 1
  • 6
  • I'm using a Windows Forms setup. – Tim Mar 18 '13 at 01:08
  • 1
    form.keypreview = true; form.onkeydown – Sam Axe Mar 18 '13 at 01:18
  • Okay, I will try adding that. I tried using that in some form from MSDN, but it kept throwing errors. Also, that solves the focus issue, but what about changing the checkstate? – Tim Mar 18 '13 at 01:22
  • What are the errors? Changing should be trivial, switch (keyPressed) ... VK_NUMPAD2 : cb2.Checked = !cb2.Checked – Martheen Mar 18 '13 at 01:26

1 Answers1

0

In your form, set the KeyPreview property to True.

Create a KeyDown event handler for the form.

The KeyDown handler should have code similar to this:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.NumPad1: 
            Toggle(checkBox1); break;
        case Keys.NumPad2:
            Toggle(checkBox2); break;
        case Keys.NumPad3:
            Toggle(checkBox3); break;
        ...
        default:
            break;
    }
}

private void Toggle(CheckBox checkbox)
{
    checkbox.Checked = !checkbox.Checked;
}

If you don't like the switch statement, another alternative is to set up a dictionary mapping the keys to the checkboxes. Then in your keydown you can check if the key is in the dictionary, and if so, get the checkbox and toggle it.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300