about UserControl and OnKeyUp, OnKeyDown and OnKeyPress

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

I wonder can somebody explain when is it suitable to
use these methods
OnKeyUp, OnKeyDown and OnKeyPress
because these raise an event. These are located in class UserControl.
If these raise an event how do I create an handler to catch these raised
events.

//Tony
 
Tony Johansson said:
I wonder can somebody explain when is it suitable to
use these methods
OnKeyUp, OnKeyDown and OnKeyPress
because these raise an event. These are located in class UserControl.
If these raise an event how do I create an handler to catch these raised
events.

You just subscribe to the KeyDown, KeyUp and KeyPress events.
 
Hello!

I know I can subscribe to these KeyDown, KeyUp and KeyPress but there
are some methods in the Control class that is named OnKeyUp(), OnKeyDown()
and
OnKeyPress() which take one perameter and that is EventArg.

I can't really see when these OnKeyXX are to be used.

Can you give a simple example to use for example OnKeyDown() ?

//Tony
 
Tony Johansson said:
I know I can subscribe to these KeyDown, KeyUp and KeyPress but there
are some methods in the Control class that is named OnKeyUp(), OnKeyDown()
and OnKeyPress() which take one perameter and that is EventArg.

Yes, and they generally raise the KeyDown, KeyUp and KeyPress events.
I can't really see when these OnKeyXX are to be used.

Can you give a simple example to use for example OnKeyDown() ?

Unless you're writing your own control at a low level, you generally
don't need to. Basically you call those methods if your control needs
to raise the appropriate events.
 
I dont really agree with that. Although there is no "need" to override these
functions when coding a control or even working in a form, I still think it
is the best thing to do in certain situations. When to use them is basically
a question of when you want to respond to a KeyDown/Up/Press. I mean this
interms of before/after/somewhere in between the other subscribers to the
event.
Say you are writing a form which wants to display the keys the user has
pressed on screen. I have seen this done for demos and screencasts to help
the views know how the form is driven. In this case you would more than
likely want to do that first, before all other event handlers have run. So in
this case you would override the method, put in the code to display the keys,
then at the end put in the call to the base implementation. You may even
decide based on your particular requirement to not call the base
implementation to swallow the event and not have anything else process it.
I you had an app which wanted to be last on a list of handlers so it could
inspect the results of all the handlers which have run before, you would
override the method, immediately call the base implementation which would
raise the event and execute all the event handlers, then put you code in
after that call to ensure it runs last.

Both these options are perfectly valid in terms of OO practices and are
better in my opinion then an object handling its own events. They will also
execute a small amount faster as they dont need to invoke delegates for the
event handler although the runtime difference would be really small.

However you decide to do, these functions are important in .NET and offer a
flexibility in turns of execution order which isnt possible with just event
handling.
 
Ciaran O''Donnell said:
I dont really agree with that. Although there is no "need" to override these
functions when coding a control or even working in a form, I still think it
is the best thing to do in certain situations.

Sometimes, yes. But unless you're actually writing a specific user
control, I think it's *usually* better to just subscribe to the events.
When to use them is basically a question of when you want to respond
to a KeyDown/Up/Press. I mean this interms of before/after/somewhere
in between the other subscribers to the event.
Say you are writing a form which wants to display the keys the user has
pressed on screen. I have seen this done for demos and screencasts to help
the views know how the form is driven. In this case you would more than
likely want to do that first, before all other event handlers have run.

You could do that by subscribing to the event handler after
construction, before anything else gets a chance to subscribe. That way
you don't need to involve inheritance at all. Personally I feel
inheritance is a heavy-handed way to effectively add an extra event
hander.

Admittedly it would be relatively hard to add something as the *last*
handler. Where necessary, you could indeed use inheritance and override
the appropriate method. I'd just treat that as a last resort instead of
a first port of call.

I wasn't trying to say that you'd *never* need to call or override the
methods - just that it wasn't particularly common. I certainly
subscribe to events *much* more often than overriding their raising
method.
 
Sometimes, yes. But unless you're actually writing a specific user
control, I think it's *usually* better to just subscribe to the events.

Well, Ciaran *did* give a specific example where it's better. You
just didn't catch it. Try harder.
You could do that by subscribing to the event handler after
construction, before anything else gets a chance to subscribe. That way
you don't need to involve inheritance at all. Personally I feel
inheritance is a heavy-handed way to effectively add an extra event
hander.

Perhaps it's heavy handed, but it works. You 'mind's eye' example
works--in your 'mind's eye'. But if you know anything about how oop
works, you'd know that there's no guarantee that the event driven
nature of C# will work the way you think it works. Here's a 'thought
experiment' for you, Einstein: you subscribe, like you say, just
after construction. But you code for the publisher/subscriber model
is kluge, and takes a long time to run. Meanwhile, other events are
firing right and left. And your program fails, since other stuff is
going on, especially if you're using multi-threaded CPUs in parallel.
Admittedly it would be relatively hard to add something as the *last*
handler. Where necessary, you could indeed use inheritance and override
the appropriate method. I'd just treat that as a last resort instead of
a first port of call.

I wasn't trying to say that you'd *never* need to call or override the
methods - just that it wasn't particularly common. I certainly
subscribe to events *much* more often than overriding their raising
method.

OH, I see. You backtracked. Now it's "not common". You use subcribe/
publish much more often--whereas I have never used it, except to
understand how it works. Overriding is conceptually easier, unless
you work in a 500 person team where nobody knows what is being worked
on, and a publish/subscribe scheme makes more sense because you're
building code for a specified series of interfaces.

RL
 
Generally, if you're creating some derived component the use of the OnXXX
protected methods are recommended because a control that subscribes to its
own events can have undesirable results when another control derives from
it. From an object orientation point of view the override is a better
choice.

As Jon points out, the base-implementation of these methods is to raise the
event and indeed, if you want to maintain that behaviour you must call the
base-class method from your derived class but this is usually done at the
end of method call after you have provided your custom behaviour.

Note that in the case of the keypress overrides, you may not get the desired
result because some keys are suppressed by the default control-key behaviour
and so never get to your control. In this case you'll need to override the
ProcessCmdKey as well if you want to trap such keys as the arrows or page-up
etc.

Below my signature is a simple user control implementation that illustrates
this.

--
--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

public partial class KeyPressControl : UserControl

{

public KeyPressControl()

{

InitializeComponent();

}

protected override void OnKeyDown(KeyEventArgs e)

{

if (Parent is Form)

{

((Form)Parent).Text = Enum.GetName(typeof(Keys), e.KeyCode);

}

base.OnKeyDown(e);

}

}
 
Admittedly I'm loathe to feed the troll, but...

raylopez99 said:
Well, Ciaran *did* give a specific example where it's better. You
just didn't catch it. Try harder.

Ciaran and I disagree. That's not a crime, and in particular it's
pretty common. I still disagree with that example. I don't claim it
won't - just that I prefer to avoid subclassing unless there's a
significant benefit.
Perhaps it's heavy handed, but it works. You 'mind's eye' example
works--in your 'mind's eye'. But if you know anything about how oop
works, you'd know that there's no guarantee that the event driven
nature of C# will work the way you think it works. Here's a 'thought
experiment' for you, Einstein: you subscribe, like you say, just
after construction. But you code for the publisher/subscriber model
is kluge, and takes a long time to run. Meanwhile, other events are
firing right and left. And your program fails, since other stuff is
going on, especially if you're using multi-threaded CPUs in parallel.

When Windows Forms starts executing event handlers in parallel, please
let me know. For one thing, all hell will break loose at that point,
given the thread affinity exhibited by WinForms.

In other words: I think you're the one who ought to learn a bit more
about how event handlers are executed. While it's possible to make them
execute in parallel, that would be very rare and *particularly* odd for
Windows Forms. I can't remember ever seeing *any* event which
parallelised its handlers. Care to provide an example?
OH, I see. You backtracked. Now it's "not common".

No backtracking involved. Let's look at what I wrote previously:

<quote>
Unless you're writing your own control at a low level, you generally
don't need to.
</quote>

Note the "generally". Generally not needing to do something sounds
pretty much like it not being a common requirement, doesn't it?
You use subcribe/ publish much more often--whereas I have never used
it, except to understand how it works.

Really? So every time you use any WinForms control you subclass it, do
you? That sounds unlikely to me.

I suspect you're actually using the pub/sub model without realising it,
if you ever write WinForms or ASP.NET code.
Overriding is conceptually easier, unless you work in a 500 person
team where nobody knows what is being worked on, and a
publish/subscribe scheme makes more sense because you're building
code for a specified series of interfaces.

Inheritance is very limiting, and comes with a number of its own
issues. Pub/sub is cleaner OO design when you fundamentally want to
react to something happening, like a button being clicked.
 
Bob Powell said:
Generally, if you're creating some derived component the use of the OnXXX
protected methods are recommended

If I were already deriving from the component I'd be *more* inclined to
override OnXXX than if it was a case of introducing inheritance solely
for the sake of reacting to the event - but I think I'd probably stick
with the event subscription unless I had a compelling concrete reason
to override the method instead.
because a control that subscribes to its own events can have
undesirable results when another control derives from it.

Could you elaborate on that? I think I've heard the same suggestion
before, but without firm details. It would be nice to know exactly what
kind of thing can go wrong.
From an object orientation point of view the override is a better
choice.

I'm not sure I'd agree - if you're conceptually wanting to respond to
the event, then adding a handler feels like it's more self-describing
to me.
 

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