Override or Event - Take 2

  • Thread starter Thread starter Publicjoe
  • Start date Start date
P

Publicjoe

OK Try again

Can someone please explain what the difference is and when to use each.

I have a form with a button dropped onto it. Without actually doing anything
to the button, I next add the following code to the form:

protected override void OnKeyDown(KeyEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.KeyCode.ToString());
base.OnKeyDown(e);
}

When you press a key, it is not handled. If you change the tabstop property
of the button to false, the key down event is now handled. Why?

However, if I put the tabstop property of the button back to true and I add
an keydown event instead:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.KeyCode.ToString());
}

When you press a key it is handled. What is happening that is different?

My understanding of what happens when you override a form method seems to be
shot to pieces.

So when should you override form methods and when should you use events?

Any clarification on this subject area would be most appreciated.

Thanks

Mike
 
With the tabstop, the button is getting focus initially; that means that it
is also getting the keypresses.

For instance; take waya the tab stop and run - press keys: both override and
event fire; now (without closing) click on the button (it gets focus); press
keys: neither override nor event fires.

By convention, OnSomeEvent wraps up firing the SomeEvent event, testing for
null etc. Overriding provides a mechanism for:
* knowing that your code (in a subclass) runs first or last, since events
are in subscriber order
* suppressing an event
* altering the parameters to an event
* slightly quicker (more noticeable in 1.1; in 2.0 delegate invokation has
been improved)

etc

Marc

My test code:

class Program : Form {
protected override void OnKeyDown(KeyEventArgs e) {
Debug.WriteLine("OnKeyDown");
base.OnKeyDown(e);
}
Program(bool tabStop) {
KeyDown += delegate { Debug.WriteLine("KeyDown"); };
Button btn = new Button();
btn.TabStop = tabStop;
Controls.Add(btn);
Text = "TabStop:" + btn.TabStop.ToString();
}
static void Main()
{
new Program(true).ShowDialog();
new Program(false).ShowDialog();
}
}
 
Generally speaking there's no difference between overriding and
attaching and event handler, other than the fact that overriding
allows you to decide if and when to call the base method.

What you're experiencing is specific to key input handling on
controls. Check the help page for the Form.KeyPreview property in the
MSDN Library for details. I don't know exactly what happened but I'm
sure it had to do with control focus issues...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top