"to determine which modifier key was pressed" question

G

Guest

In the .NET 2003 docs, it says to use the following code for an event handler
to determine which modifier key was pressed when an event is fired:

Private Sub Button1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Button1.KeyPress
If (Control.ModifierKeys And Keys.Shift) = Keys.Shift Then
MessageBox.Show("Pressed " & Keys.Shift)
End If
End Sub

My question: Why did MS elect to use a shared member of the Control class
(Control.ModifierKeys) instead of adding a member of the same name to the
KeyPressEventArgs class to hold this information for the time the event was
fired? To me, this approach would have been more encapsulated. More
importantly, won't Control.ModifierKeys hold incorrect information if the
user changes the state of Control.ModifierKeys before the event handler
fires? Unlikely sure, but I would think it is possible.

Any insight would be appreciated.
Thanks!
SolarCoder
 
M

Morten Wennevik

Hi SolarCoder,

The Control.ModifierKeys is useful when dealing with any events,
especially mouse events, and not just key events. Since KeyPress isn't
actually a key event but more like a character event I suppose they opted
to not have a ModifierKeys property inside the KeyPress event since you
can just as well use Control.ModifierKeys.
 
G

Guest

You are correct, and your observation applies to mouse up/down events where
access to modifier keys is also by shared Control.ModifierKeys. In practice,
I have not been inconvenienced by this MS oversight.
 
G

Guest

Thanks to Morten Wennevik & AMercer!

Looks like this is one I will have to put in the "I don't why they did it
that way" category, but it is something I can certainly live with as long as
the behavior is deterministic.

Just one of those things that bugged me more than my code.
Thanks!
-SC
 

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

Top