PDA

View Full Version : Solved: Need help with KEYPRESS



marshallgrad
09-09-2008, 06:26 AM
I am trying to design a new FORM so that when I press a certain key on the numeric keypad, it will tally/register and update the count in a TEXTBOX.

To keep it short, I have a FORM and I want to put a LABEL1 and TEXTBOX1 on it. When I press the #1 key on the numeric keypad, I want the TEXTBOX1 value to increment and update with each press of the key. Can someone show how this might be accomplished and is a TEXTBOX the best choice to use as the tally box?

Thanks,
Butch

Demosthine
09-27-2008, 05:55 PM
Hey there.

There are several ways to handle this. But first you need to realize that for the most part, the KeyPress Event only works with the Control you are programming it for. It is difficult to do a program-wide or form-wide event like that.

But that being said, I would start out with a form that has the number of l labels for the number of keys you are trying to capture. If you are only doing letters, it would be 26 x 2 = 52.

I would recommend using labels because they don't receive the focus like a Textbox does. THe user can not select and update the value in the Label, either.

Once you have all of the labels on the Form, rename the Label that will be static and display the letter you are tallying something like 'lblA' thru 'lblZ' and arrange them however you want them.

Second, align the second set of labels and name them something like 'lblTallyA' thru 'lblTallyZ' so that you can access is via name rather than having to hardcode each Select Case.

From there, you should be able to do a loop using code similar to the below.


Option Explicit
Private Sub Form_KeyPress(KeyAscii As Integer)
On Error Resume Next

With frmKeyPress
Select Case KeyAscii
Case Asc("0") To Asc("9")
.Controls("lblTally" & Chr(KeyAscii)).Caption = _
.Controls("lblTally" & Chr(KeyAscii)).Caption + 1
Case Else
End Select
End With
End Sub



In the above example, I only created Labels for Keys 0 thru 9 for simplicity sake. You should very easily be able to take the idea for the other 94 keys on a standard keyboard...

If you need additional help, let me know.
Scott

Bob Phillips
09-28-2008, 04:03 PM
But first you need to realize that for the most part, the KeyPress Event only works with the Control you are programming it for. It is difficult to do a program-wide or form-wide event like that.

It is not difficult to do it for all controls of a similar type using application events to simulate a control array. Not all events are exposed to the application in this way, but KeyPress is.