473,581 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

about UserControl and OnKeyUp, OnKeyDown and OnKeyPress

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
Jul 6 '08 #1
8 4257
Tony Johansson <jo************ *****@telia.com wrote:
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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 6 '08 #2
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
"Jon Skeet [C# MVP]" <sk***@pobox.co mskrev i meddelandet
news:MP******** *************@m snews.microsoft .com...
Tony Johansson <jo************ *****@telia.com wrote:
>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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com

Jul 6 '08 #3
Tony Johansson <jo************ *****@telia.com wrote:
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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 6 '08 #4
Ciaran O''Donnell <Ci************ @discussions.mi crosoft.comwrot e:
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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 7 '08 #5
On Jul 7, 11:17*am, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Ciaran O''Donnell <CiaranODonn... @discussions.mi crosoft.comwrot e:
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.
Well, Ciaran *did* give a specific example where it's better. You
just didn't catch it. Try harder.
>
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.
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
Jul 7 '08 #6
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 ()

{

InitializeCompo nent();

}

protected override void OnKeyDown(KeyEv entArgs e)

{

if (Parent is Form)

{

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

}

base.OnKeyDown( e);

}

}

"Tony Johansson" <jo************ *****@telia.com wrote in message
news:c3******** ******@newsb.te lia.net...
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
"Jon Skeet [C# MVP]" <sk***@pobox.co mskrev i meddelandet
news:MP******** *************@m snews.microsoft .com...
>Tony Johansson <jo************ *****@telia.com wrote:
>>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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com

Jul 8 '08 #7
Admittedly I'm loathe to feed the troll, but...

raylopez99 <ra********@yah oo.comwrote:
Ciaran O''Donnell <CiaranODonn... @discussions.mi crosoft.comwrot e:
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.

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.
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.
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?
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".
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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 8 '08 #8
Bob Powell [MVP] <bo*@spamkiller bobpowell.netwr ote:
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.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 8 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
18718
by: Matthew | last post by:
Is there anyway to tweak this to ignore the function() only if the Tab key is pressed? onkeydown="javascript:function();"
6
3900
by: Z | last post by:
I have sub-classed the TextBox. In its OnKeyDown event I can intercept key strokes, examine them, etc. When I get a certain keycode (e.g., 'A') I want to change it to another unicode key from a different code page (e.g., "\u2801"). But the KeyCode, KeyData, and KeyValue properties of KeyEventArgs are all only getters. They are read only and...
4
9993
by: KublaiKhan | last post by:
I am trying to figure out what values are returned when keys are pressed in Mozilla & IE. Here's the code I'm using. There are no alerts in either browser. Any clues would be greatly appreciated. Thanks. KK <html> <head><title>Reading Keystrokes</title> <script language="JavaScript"> window.onkeyDown = keyHit;
0
1293
by: bj | last post by:
Hello Recently i've found very interesting problem i made new class derived from UserControl and i need to process arrow keys movments but OnKeyDown method seems to all keys besides arrow keys however OnKeyUp method works just fine for the same arrow keys , moreover OnKeyDown works when i press arrowkeys + modifiers keys like CTRL, so...
2
1813
by: William Barnes | last post by:
Using VS .NET 2003 on an up-to-date XP Pro machine: I'm getting bizarre results in a VB Windows app trying to implement the OnKeyUp event handler. I have a form with a label control and code simialr to the following: Protected Overrides Sub OnKeyUp(ByVal e As System.Windows.Forms.KeyEventArgs) Select Case e.KeyCode
3
4027
by: Brad | last post by:
The first text on my form is a numeric field. I have a javascript that runs on this field for onkeyup (validate the key strokes and modifies fields on the screen) but when I do this and have the autopostback on, the autopostback does not trigger. The autopostback will trigger if I hit the enter key while in the textbox but not when I leave...
4
4986
by: Udi | last post by:
Hi All, MyRichEdit is derived from RichTextBox. I'm overriding OnKeyDown. I'm trying to handle the TAB key but without printing it in the edit box: protected override bool IsInputKey(Keys keyData) { switch (keyData) {
2
1799
by: alkalsa | last post by:
Happy 2007 all... :-) I am looking for a way in JavaScript in IE 7.0 only, to have it detect the Backspace key on the keyboard. So like, <script> if backSpaceKeyPressed {
3
2552
by: gjain12 | last post by:
Hi all, I am using the following code to disable the ctrl+a/c/v/x keys. <html> <head> <script language="JavaScript" type="text/javascript"> function disableCtrlKeyCombination(e) { //list all CTRL + key combinations you want to disable
0
8137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8299
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7890
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6545
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5355
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3799
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1127
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.