1

I'm trying to make a user interface simple with 2 buttons 1 starts a loop and the other one stops it

The only thing I could come up with is to create a global variable that changes depending on which button is pressed and that's the condition for the loop however the stop button won't work while the loop is running and therefore i can't stop the loop

Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public StartStop As Integer
Public para As Integer

Sub AutoClick(x)

Do While StartStop = 1
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    Sleep (x * 1000)
    If para = 0 Then
        Exit Do
    End If
Loop


End Sub


Private Sub CommandButton1_Click() 'this is the start button

StartStop = 1
para = 1
AutoClick (Segundos)

End Sub

Private Sub CommandButton2_Click() 'this is the stop button
para = 0
End Sub

Id just like for the stop button to stop the loop, but I haven't come up with an answer yet, don't wanna overcomplicate the code for this

Dip Hasan
  • 225
  • 3
  • 9
  • 1
    What do you want to achieve with the `mouse_event`-statements? And what is the real purpose of the loop? – FunThomas Jan 10 '19 at 15:14
  • @FunThomas It looks like the attempt at an autoclicker. I'd assume for simply academic purposes? As there are many free and perfectly functional autoclickers available. And the question aims to solve the problem of stopping the program once it has been set in motion. I think [Asse3mbler's answer](https://stackoverflow.com/a/54131586/7778672) should work. – Inarion Jan 11 '19 at 08:51

2 Answers2

1

You should add a DoEvents function invocation inside your loop, as described in this answer

Do While StartStop = 1
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    Sleep (x * 1000)
    DoEvents
    If para = 0 Then
        Exit Do
    End If
Loop
Ass3mbler
  • 3,855
  • 2
  • 20
  • 18
-1

Check this:

Dim i As Long
Dim doloop As Boolean

Private Sub CommandButton1_Click()
    doloop = True
    StartCicle
End Sub

Private Sub CommandButton2_Click()
    doloop = False
End Sub


Sub StartCicle()

    i = 0
    While doloop

        Label1.Caption = CStr(i)
        i = i + 1
        DoEvents

    Wend
End Sub

Put this code on a UserForm and add 2 commandbuttons and a label.

Click on commandbutton1 to start cicle Click on commandbutton2 to stop cicle You can see label 2 being incremented

That code do what you want.

Jorge Ribeiro
  • 1,128
  • 7
  • 17