Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting Info while a key is held down

Status
Not open for further replies.

domt

Programmer
Mar 13, 2001
115
US
How can I have a label count up a number (perhaps with a large divisor) while and as long as a particular key is held down?
 
Use the form's KeyDown or KeyPress event and check for the key being pressed.

If it is the correct key, just add 1 to the previous value.

Label1.Caption = Cstr(Clng(Label1.Caption) + 1)
 
CCLINT
Thanks for your reply.
I've been playing around with the KeyPress event but can't get it to do what I want.
What I'd like is to have a variable increase from zero to some value, say 10000, while I hold down one key, say the F2 key, and decrease if I hold down another key, say F1.
Can you suggest some code to do this?
domt
 
If you want to use Function keys use the KeyDown event exactly as CCLINT says - you need to use the predefined values to test against such as vbKeyF1.

Keypress only works on printable keys, not function keys or arrows


________________________________________________________________
If you want to get the best response to a question, please check out FAQ222-2244 first

'People who live in windowed environments shouldn't cast pointers.'
 
In the KeyDown event:

If Ascii=vbKeyF1 Then
'add
End If
 
I think this is what you mean:-

You need to add a Timer control to your form then:

Dim Counter As Long

Private Sub Form_Load()
Timer1.Interval = 100
Timer1.Enabled = False
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyF1 Then
Timer1.Enabled = True
End If
End Sub

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyF1 Then
Timer1.Enabled = False
End If
End Sub

Private Sub Timer1_Timer()
Counter = Counter + 1
Label1 = Counter
End Sub

You will need to expand the code to add or subtract the counters value according to the keydown/keyup events.

Good luck
 
Yes, I did make the mistake and wrote Acsii instead of KeyCode:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbKeyF1 Then
If Not IsNumeric(Label1.Caption) Then
Label1.Caption = "1"
Else
Label1.Caption = CStr(CLng(Label1.Caption) + 1)
End If
End If
End Sub

But, bigalbigal, why are you suggesting the use of a timer here? What advantage does it have?

If you hold the key long enough, the KeyDown event will repeatedly fire anyways.
 
CCLINT... I didn't know that, but there again, I have never needed to trap a key event in this way.

Thanks for the knowledge.

Big Al
 
This has been instructive.
Thank you all for your replies.
Domt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top