Visual Basic Counter Script

I'm in search for a code in which does the following:

when F1 is pressed, then add 1 to the counter
when F2 is pressed, then add 2 to the counter
when counter is equal to or greater than 4, then send key F1 and take 5 away from the counter (i dont want to reset the counter, just take away 5 from it)

Counter then resets if F1 or F2 have not been pressed for 10 seconds.

I need it to be able to run as an .exe code in which i can double click to open and run.

Any help would be much appreciated.
kakashisharingunAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dirk HaestProject managerCommented:
>> when counter is equal to or greater than 4, then send key F1 and take 5 away from the counter

So add 1 and subtract 5 ? Why not subtracting 4 at once ?


Below an example of a small app (just a window application in VB.NET)
Private counter As Integer
    Private WithEvents timeOut As Timer

    Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        timeOut.Stop()
        ' Pressed F1
        If (e.KeyValue = 112) Then
            counter += 1
        End If
        If (e.KeyValue = 113) Then
            counter += 2
        End If
        If counter > 4 Then
            counter -= 4
        End If
        timeOut.Start()
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        timeOut = New Timer()
        timeOut.Interval = 10000
        counter = 0
    end sub

    Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timeOut.Tick
        counter = 0
        timeOut.Stop()
    End Sub

Open in new window

0
Chris Raisin(Retired Analyst/Programmer)Commented:
Do you want this application to run in the background while running another application, or are you simply wanting it to run as the main application while you hit F1 and F2 while reading (for example) data from a sheet (perhaps you are wanting to use these keys as a sort of "mini adder" of the number of times these keys are pressed?)

It will make a great edal of difference if you want the F1 and F2 keys to be sensed while running another application.

Please advise....
0
Chris Raisin(Retired Analyst/Programmer)Commented:
I have created a small application for you.

Download it from the following link:

  https://filedb.experts-exchange.com/incoming/ee-stuff/8076-F1F2Counter.zip 

The code is showing below.
It is VB6 but has full comments just in case you are not a VB6 guru.

If you need the program to sense F1 or F2 when keying into OTHER programs (e.g. Notepad, Word, etc). things will have to be re-written slightly.

Hope this is what you are after.
'Code to be placed inside a module called "Module1.bas"
Option Explicit
'when F1 is pressed, then add 1 to the counter
'when F2 is pressed, then add 2 to the counter
'when counter is equal to or greater than 4, then send key F1 and take 5 away from the counter (i dont want to reset the counter, just take away 5 from it)
'Counter then resets if F1 or F2 have not been pressed for 10 seconds.

Declare Function SetTimer Lib "user32" _
            (ByVal hwnd As Long, _
            ByVal nIDEvent As Long, _
            ByVal uElapse As Long, _
            ByVal lpTimerFunc As Long) As Long

Declare Function KillTimer Lib "user32" _
            (ByVal hwnd As Long, _
            ByVal nIDEvent As Long) As Long

Global nCounter As Integer      ' the counter to keep track of values
Global bKeyPressed As Boolean   'a flag to remember if a key has been pressed

Sub TimerProc(ByVal hwnd As Long, _
              ByVal uMsg As Long, _
              ByVal idEvent As Long, _
              ByVal dwTime As Long)
  If Not bKeyPressed Then
    nCounter = nCounter - 4
    Form1.txtCounter.Text = CStr(nCounter) 'if no key pressed in last interval, reset the counter to zero
  Else
    bKeyPressed = False  'start new interval looking for a key to be pressed
  End If
End Sub

Private Sub Main()
  Form1.Show vbModal
End Sub



'=====================================================================

'Code to be placed inside a form called "Form1.frm"
Option Explicit
Public lngTimerId As Long     'Pointer to timer instance
Private Sub Form_Load()
  'Keypreview must be set to true for key presses to be sensed
  Form1.KeyPreview = True
End Sub
Private Sub cmdClose_Click()
  StopTimer  'must stop timer before closing program.
  Unload Me
  End
End Sub
Private Sub cmdStop_Click()
  StopTimer
  lblRunning.Caption = ""
  cmdStart.Enabled = True
  cmdClose.Enabled = True
  cmdStop.Enabled = False
  cmdStart.SetFocus
End Sub
Private Sub StopTimer()
  lngTimerId = KillTimer(0, lngTimerId)
  If lngTimerId > 2 Then
    MsgBox "Couldn't stop the timer! Stopping program."
    End
  End If
End Sub
Private Sub cmdStart_Click()
  lngTimerId = SetTimer(0, 0, 10000, AddressOf TimerProc)
  If lngTimerId = 0 Then
    MsgBox "Could not create Timer! Ending Program."
    Exit Sub
  Else
    nCounter = 0
    txtCounter.Text = "0"         'Reset the counter to zero
    lblRunning.Caption = "Running..."
    cmdStart.Enabled = False
    cmdStop.Enabled = True
    cmdClose.Enabled = False
    Form1.SetFocus 'make sure the form is ablke to sense keystrokes
  End If
End Sub
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
   'only increment counter if application is running.....
   If Me.cmdStop.Enabled = True Then
     Select Case KeyCode
       Case vbKeyF1
         nCounter = nCounter + 1     ' Add 1 to counter
         bKeyPressed = True          ' remember that a key has been pressed
       Case vbKeyF2
         nCounter = nCounter + 2     ' Add 1 to counter
         bKeyPressed = True          ' remember that a key has been pressed
     End Select
     txtCounter.Text = CStr(nCounter) 'show the new value of the counter
   End If
End Sub

Open in new window

0.jpg
1.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Chris Raisin(Retired Analyst/Programmer)Commented:
Oh..this final screenshot is for a label which is not evident when the form first shows. Set it's caption to "" (empty sctring) rather than "Running...."
(the caption is showing here just to make it clear what the set-up is on the form).
In fact, it may be a good idea to change the procedure "Form_Load" to the following:
Private Sub Form_Load()
  'Keypreview must be set to true for key presses to be sensed
  Form1.KeyPreview = True
  Form1.lblRunning.Caption = ""
End Sub

Open in new window

8.jpg
0
Chris Raisin(Retired Analyst/Programmer)Commented:
Oops! again...should say "Running..." not "Hidden..."  LOL...my mind was wandering.....
8.jpg
0
Chris Raisin(Retired Analyst/Programmer)Commented:
One final thought....

Every time a key is pressed, be aware that a new 10 second interval does not start. It could happen that a key is pressed at 7 seconds.
At the 10 seconds interval, the timer will sense a key has been pressed and will wait a further 10 seconds to check the next keypress (an total interval of 13 seconds in fact).

Does this matter?  If so, the timer will have to be adjusted as shown in this re-write of the code as showing below. Notice that the "flag" to remember if a key has been pressed is now gone..

I have uploaded this altered version (version 2) here:

     https://filedb.experts-exchange.com/incoming/ee-stuff/8079-F1F2Counter_V2.zip
     
'Place this code inside a form called Form1
Option Explicit
Public lngTimerId As Long     'Pointer to timer instance
Private Sub Form_Load()
  'Keypreview must be set to true for key presses to be sensed
  Form1.KeyPreview = True
End Sub
Private Sub cmdClose_Click()
  StopTimer  'must stop timer before closing program.
  Unload Me
  End
End Sub
Private Sub cmdStop_Click()
  StopTimer
  lblRunning.Caption = ""
  cmdStart.Enabled = True
  cmdClose.Enabled = True
  cmdStop.Enabled = False
  cmdStart.SetFocus
End Sub
Private Sub StopTimer()
  lngTimerId = KillTimer(0, lngTimerId)
  If lngTimerId > 2 Then
    MsgBox "Couldn't stop the timer! Stopping program."
    End
  End If
End Sub
Private Sub cmdStart_Click()
  lngTimerId = SetTimer(0, 0, 10000, AddressOf TimerProc)
  If lngTimerId = 0 Then
    MsgBox "Could not create Timer! Ending Program."
    Exit Sub
  Else
    nCounter = 0
    txtCounter.Text = "0"         'Reset the counter to zero
    lblRunning.Caption = "Running..."
    cmdStart.Enabled = False
    cmdStop.Enabled = True
    cmdClose.Enabled = False
    Form1.SetFocus 'make sure the form is ablke to sense keystrokes
  End If
End Sub
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
   'only increment counter if application is running.....
   If Me.cmdStop.Enabled = True Then
     Select Case KeyCode
       Case vbKeyF1
         nCounter = nCounter + 1     ' Add 1 to counter
         ResetTimer
       Case vbKeyF2
         nCounter = nCounter + 2     ' Add 1 to counter
         ResetTimer
     End Select
     txtCounter.Text = CStr(nCounter) 'show the new value of the counter
   End If
End Sub
Private Sub ResetTimer()
  StopTimer
  DoEvents   'make sure the windows system rocesses background stuff to stop timer
  'restart the timer
  lngTimerId = SetTimer(0, 0, 10000, AddressOf TimerProc)
  If lngTimerId = 0 Then
    MsgBox "Could not create Timer! Ending Program."
    End
  End If
End Sub

'=================================================================
'Place this code inside a module called Module1.bas
Option Explicit
'when F1 is pressed, then add 1 to the counter
'when F2 is pressed, then add 2 to the counter
'when counter is equal to or greater than 4,
'then send key F1 and take 5 away from the counter
'(i dont want to reset the counter, just take away 5 from it)
'(this is in effect the same as taking 4 away from it!)
'Counter then resets if F1 or F2 have not been pressed for 10 seconds.

Declare Function SetTimer Lib "user32" _
            (ByVal hwnd As Long, _
            ByVal nIDEvent As Long, _
            ByVal uElapse As Long, _
            ByVal lpTimerFunc As Long) As Long

Declare Function KillTimer Lib "user32" _
            (ByVal hwnd As Long, _
            ByVal nIDEvent As Long) As Long

Global nCounter As Integer      ' the counter to keep track of values

Sub TimerProc(ByVal hwnd As Long, _
              ByVal uMsg As Long, _
              ByVal idEvent As Long, _
              ByVal dwTime As Long)
    If nCounter > 4 Then
      'if the counter value is greater than 4 then
      nCounter = nCounter - 4
      Form1.txtCounter.Text = CStr(nCounter) 'if no key pressed in last interval,
                                             'reset the counter to new value
    End If
End Sub

Private Sub Main()
  Form1.Show vbModal
End Sub

Open in new window

0
Chris Raisin(Retired Analyst/Programmer)Commented:
Upon re-reading your criteria, I gather you smply want to reduce the counter by 5 when the time has elapsed.

Amend the lines in "TimerProc" as showing below.
 
'This version if you want the counter to have 5 "subtracted"
'only if the value is greater than 4  
Sub TimerProc(ByVal hwnd As Long, _
              ByVal uMsg As Long, _
              ByVal idEvent As Long, _
              ByVal dwTime As Long)
    If nCounter > 4 Then
      'if the counter value is greater than 4 then
      nCounter = nCounter - 5
      Form1.txtCounter.Text = CStr(nCounter) 'if no key pressed in last interval,
                                             'reset the counter to new value
    End If
End Sub


'This version if you want the counter to have 5 "subtracted"
'if the value is greater than 4 else revert to zero. 
Sub TimerProc(ByVal hwnd As Long, _
              ByVal uMsg As Long, _
              ByVal idEvent As Long, _
              ByVal dwTime As Long)
    If nCounter > 4 Then
      'if the counter value is greater than 4 then
      nCounter = nCounter - 5
    else
      nCounter = 0   
    endif
    Form1.txtCounter.Text = CStr(nCounter) 'if no key pressed in last interval,
                                           'reset the counter to new value
End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Chris Raisin(Retired Analyst/Programmer)Commented:
Any further developments?
0
kakashisharingunAuthor Commented:
WOW That's absolutely amazing there - So much work seems to be put into it too - I'm utterly impressed. Thanks, this is all perfect - I wish I could give you more points!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.