I have a problem with setting the same event handler for all controls on the form.
I want to handle pressed f5-f7 buttons uniformly in my application, so I try to register the same event handler for all 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 InitializeComponent() function just before automatically generated ResumeLayout/PerformLayout calls. Don’t mind the the name MainForm_KeyPress, it’s actually a KeyDown event handler now.
I also tried to insert the code in my init() function which is called from constructor.
But result was the same: the event does not occur when I press keys. Focus is on one of form’s buttons.
But if I implement the handler for one of the buttons using design tool (copy function name to KeyPress event field), the event raises correctly if the button is in focus.
Any ideas why foreach didn’t work?
MSDN says you can do with with setting KeyPreview to true.