Search code examples
c#winformskeyboardkeyevent

Register Modifier keys for a CustomControl


I am working on a CustomControl and I want to register ModifierKeys in this control. I have already set the KeyPerview to True in the Form which this control is being added to.

Now I have a Boolean named _ctrl and I want this boolean to be true when the Control key is being held down and it should be false when Control key is being released.

I tried to achive this with the conde belowe in my CustomControl but no success!

private bool _ctrl = false;

private void MyCustomControl_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.Control)
    {
        _ctrl = true;
    }
}

private void MyCustomControl_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Control)
    {
        _ctrl = false;
    }
}

Any tips/soloution will be appriciated!

UPDATE

Ok, I decided to do the key down and up event in the form itself:

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.Control)
        {
            projectBrowser.ControlKeyIsDown = true; //bool in MyCustomControl
            MessageBox.Show("CTRL is PRESSED");
        } 
     }

    private void MainForm_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == Keys.Control)
        {
            projectBrowser.ControlKeyIsDown = false; //bool in MyCustomControl
            MessageBox.Show("CTRL is DEPRESSED");
        } 
    }

Now, The KeyDown event detects the control key and messagebox is being shown. But the KeyUp event does not work and it doesn't show the messagebox. What could be wrong?

It seems that the key up gets detected if I change the KeyUpevent like this:

private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.LControlKey || e.KeyCode == Keys.RControlKey || e.KeyCode == Keys.ControlKey || e.KeyCode == Keys.Control)
    {
        projectBrowser.ControlKeyIsDown = false;
        e.Handled = true;
    }
}

Solution

  • You can try calling the Control.ModifierKeys property:

    protected override void OnKeyDown(KeyEventArgs e) {
      if (Control.ModifierKeys == Keys.Control) {
        MessageBox.Show("I am pressing control.");
      }
      base.OnKeyDown(e);
    }
    

    If you throw up a MessageBox on the KeyDown event, the KeyUp event won't get called.