One event handler for all controls on the form

I have a problem setting up the same event handler for all controls on the form. I want to handle the pressed f5-f7 buttons evenly in my application, so I'm trying to register the same event handler for all the controls on the form. I inserted

foreach (System.Windows.Forms.Control cont in this.Controls)
                cont.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainForm_KeyPress);

in the InitializeComponent () function before automatically creating ResumeLayout / PerformLayout calls. Ignore the name MainForm_KeyPress, it is actually a KeyDown event handler.

I also tried pasting the code into my init () function, which is called from the constructor. But the result was the same: the event does not occur when I press the keys. Focus is on one of the form buttons.

But if I implement a handler for one of the buttons using the design tool (the name of the copy function in the KeyPress event field), the event will be correctly raised if the button is in focus.

Any ideas why foreach didn't work?

+5
source share
2 answers

MSDN says what you can do with setting KeyPreview to true.

+6
source

Perhaps you need to overwrite and register it for the child controls of each control that you encounter in the tree?

, , {} , " " + . , , . , , ? -, - , , , .

, : , , WM_. - WM_ .NET , , , .. WM_ , , , .

, , , , , bool, , , , dockmanager , , , , , , , .

+1

All Articles