'cannot trap Up or Down keys...

ALX

Well-known member
Joined
Nov 16, 2005
Messages
253
Location
Columbia, SC
Programming Experience
10+
I have a small message form set up with 5 or so labels and a cancel button. I want the labels to change background color as the user presses the up or down keys. It seems that I can trap all key events except the up and down keys. I've tried many combinations of:
-----------------------------------
VB.NET:
Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs) 
          If e.KeyChar = ChrW(38) Then 
               e.Handled = True
               '<...process color here ...>
          Else 
               MyBase.OnKeyPress(e) 
          End I
-----------------------------------

VB.NET:
 Private Sub Form1_KeyPress (ByVal sender As Object, ByVal e As _
 system.Windows.Forms.KeyPressEventArgs) _ Handles MyBase.KeyPress
           If e.KeyChar = ..... an so on ...
-----------------------------------
The KeyPreview for the form is set to TRUE. I've tried versions using the
VB.NET:
 "AddHandler KeyDown, AddressOf ..."
method. Nothing seems to be able to trap the arrow keys. I prefer using labels rather than buttons on this form because it is used mostly as messaging window and only needs to be able to highlight selected labels for one or two short applications.
I'm using Visual Studio.NET 2003...... 'Any ideas what I'm doing wrong ?
 
OK... That's good. That means my software is up to snuff now.
Now here's the last remaining issue, now that my arrow keys are being trapped properly...
When there are only labels on the form, the arrow keys allow the user to cycle through the label selections just fine. As soon as I add a button or two to the form, say for Cancel or OK buttons, the form looses control over trapping the arrow key events for the labels. When the arrow keys are pressed now, the focus just shifts between the two button controls and the event trapping that I used to have when the form contained only the labels is gone. I assume this is where the "IsInputKey" method for the controls comes into play. The Help section in VS2003 isn't much help here. Can you shed any light on this?
 
That's the standard behaviour and that's the Buttons handling the keyboard events. If you want your form to handle those events then you need to set the KeyPreview to True and you would need to set e.Handled to True in the event handler so that the event doesn't get passed on to the currently focused control. Note that you should ONLY set e.Handled to True if you do indeed handle the event, which presumably means only for arrow keys.
 
Back
Top