By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,136 Members | 1,089 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,136 IT Pros & Developers. It's quick & easy.

Control.KeyDown

P: 8
Control.KeyDown, C#.NET

I have a user control with several controls on it. I had the same code in all the controls to call the Winhelp or DO SOME STUFF. The code basically captured the F1 Key when the control had the focus. All worked fine, but I had up to 20 controls on a form and the same snippet of code below had to basically be repeated 20 times

1. Create an event for Control in IntitializeComponent()
this.MyTextBox.KeydDown += new System.Windows.Fomrs.KeyEventHandler(this.MyTextBo x_EventName);

2. Create the Event Handler for For the Above Control.KeyDown event

private void MyTextBox_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.F1)
{
DO SOME STUFF HERE;
}
}

I then made the code generic see the snippet below and used one routine for all the controls. Now the Event Handler is never called, nothing happens. What is missing or what else is needed for a simple solution?

Below is the Scenario

1.Create a generic event for all controls on the form in IntializeComponents()
this.KeydDown += new System.Windows.Forms.KeyEventHandler(this.MyGeneri c_EventName_KeyDown);

2 .Create a generic event handler for all The Controls that we are interested in.

private void MyGeneric_EventName_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox || c is ComboBox || c is CheckBox)
{
if (e.KeyCode == Keys.F1)
{
DO SOME STUFF HERE;
}
}
}
}
Sep 6 '06 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.