-1

I have a window that include UserControl then I need to track Ctrl + i in order to do it I use this approach

        public RecordTab()
        {
            KeyDown += new KeyEventHandler(RecordTab_KeyDown);
            ...
        }

        public void RecordTab_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.I)
            {
                Console.WriteLine("HERE!!!");
            }
            else
            {
                Console.WriteLine("NOTHING!!!");
            }
        }

When I click any buttons nothing happens

What am I doing wrong?

Sirop4ik
  • 4,543
  • 2
  • 54
  • 121
  • Perhaps a typo mistake in the question : `TV_RecordTab_KeyDown` or `RecordTab_KeyDown` ? –  Dec 06 '20 at 13:15
  • Is "RecordTab" the window or the usercontrol? – Idle_Mind Dec 06 '20 at 13:35
  • 3
    The KeyDown event is raised on the control that has the focus. That will never be the UserControl, it has no use for focus and doesn't want it, passing it to one of its child controls instead. You can [override ProcessCmdKey()](https://stackoverflow.com/a/400325/17034) in the user control class if you want to detect the keystroke regardless of which specific child control has the focus. – Hans Passant Dec 06 '20 at 13:39
  • Do you need the handler called on the user control background like with the code provided or on an embedded control like a textbox ? If you need all control and the background catch keys, you should override the `ProcessCmdKey(ref Message msg, Keys keyData)` method or add handler for all child controls including `this` (can be automated in a single line). –  Dec 06 '20 at 13:48

1 Answers1

2

You may want to use this code in your UserControlName.cs file

private const Keys Target = Keys.Enter | Keys.Control;

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == Target)
        {
            Console.WriteLine("HERE!!!");
            return true;
        }
        else
        {
            Console.WriteLine("NOTHING!!!");
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }
Usama Aziz
  • 169
  • 1
  • 10