Toggle a while loop to turn it off and on.

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
lightright
Posts: 11
Joined: 13 Mar 2023, 19:20

Toggle a while loop to turn it off and on.

Post by lightright » 21 Mar 2023, 23:11

This is the code that I wrote.

Code: Select all

mainGui := Gui(,"HELP")


mainGui.Add("Button", "x550 y300", "test").Onevent("click", test)
mainGui.Add("Button", "x550 y330", "test2").Onevent("click", test2)
num := mainGui.Add("Text", "x550 y280 w30", "1")

mainGui.Opt("+AlwaysOnTop +ToolWindow")
mainGui.Show("x0 y510 w640 h350")

Stop := true


test(_obj, * )
{
	while(Stop)
	{
		num.value++
		Sleep(100)
	}
}

test2(_obj, * )
{
	global Stop := !Stop
}
Currently, I have to press the Test2 button twice in order to re-run the program after pressing the Test1 button.

What I want is to use the Test1 button as a toggle.

I want to write a code where when I press the Test1 button, its name changes to "Stop" and the program runs, and when I press the renamed "Stop" button again, its name changes back to "Test1" and the program stops.

Can you help me with how to write the code?

User avatar
mikeyww
Posts: 27095
Joined: 09 Sep 2014, 18:38

Re: Toggle a while loop to turn it off and on.

Post by mikeyww » 22 Mar 2023, 05:17

Code: Select all

; This script shows a "stopwatch": a number that increases at a defined interval
#Requires AutoHotkey v2.0
startName := 'Test1'
incr      := () => num.Value++
gui1      := Gui(), gui1.SetFont('s10')
gui1.AddButton('w230', startName).OnEvent('Click', Test1_Click)
gui1.SetFont('s14 w600 cBlue')
num       := gui1.AddText('wp Center', 0)
gui1.Show

Test1_Click(btn, info) {
 If btn.Text = startName
      SetTimer(incr, 100), btn.Text := 'Stop'   , SoundBeep(1500)
 Else SetTimer(incr,   0), btn.Text := startName, SoundBeep(1000)
}

Post Reply

Return to “Ask for Help (v2)”