Get the Event Performed on a Control
I am hoping for some help.
In my application, I have a Text Box which should display the event occure开发者_开发百科d in any control while clicking it.
For exmaple, if I click on a button or a checkbox in the app., the text box should identify the event and display as button1.clicked, checkbox1.checked kind of things.
Can anyone help me to get this done.
Thanks In Advance.:)
If you want to do it for all controls dynamically you can navigate through the controls tree and subscribe the same event handler for events like shown below, in case of predefined controls set basically just subscribe all of them for the same even handlers.
Predefined controls set
checkBox1.CheckedChanged += (s, e) => { /* handles Checked state changes*/ };
button1.Click += (s, e) => { /* handles button click */ };
Dynamic
private void InitializeHooks()
{
foreach(var control in this.Controls)
{
var button = control as Button;
if (button != null)
{
button.Click += OnClick;
continue;
}
var checkBox = control as CheckBox;
if (checkBox != null)
{
checkBox.CheckedChanged += OnCheckedChanged;
}
}
}
// Button click handler
private void OnClick(object sender, EventArgs eventArgs)
{
txtOutput.Text = String.Format(
CultureInfo.CurrentCulture,
"{Control Type: {0}, Name: {1}, Event: Click",
sender.GetType().Name,
sender.Id);
}
// Checkbox Checked state changed handler
private void OnCheckedChanged(object sender, EventArgs eventArgs)
{
txtOutput.Text = String.Format(
CultureInfo.CurrentCulture,
"{Control Type: {0}, Name: {1}, Event: CheckedChanged",
sender.GetType().Name,
sender.Id);
}
精彩评论