4

I am making AutoIt code and one of the items on the GUI needs to be updated every few seconds, and I can seem to get it to do it. To make it simple I have written some code that shows the problem:

$num = 0
GUICreate("Example")
$Pic1 = GUICtrlCreateLabel($num, 10, 10)
GUISetState()
While 1
   sleep(1000)
   $num = $num + "1"
WEnd

If the code was working then the number would change, but it does not. How do I make it refresh?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
09stephenb
  • 9,358
  • 15
  • 53
  • 91

3 Answers3

5

The number is updating, but your data is not. Plus, you are mixing integers with strings.

Luckily AutoIt converts them automatically. But take care, because you will have problems in other programming languages.

Here you go:

Local $num = 0
Local $hGUI = GUICreate("Example")
Local $Pic1 = GUICtrlCreateLabel($num, 10, 10)
GUISetState()

Local $hTimer = TimerInit()
While 1
    ;sleep(1000)
    If TimerDiff($hTimer) > 1000 Then
        $num += 1
        GUICtrlSetData($Pic1, $num)
        $hTimer = TimerInit()
    EndIf

    If GUIGetMsg() = -3 Then ExitLoop
WEnd

P.S.: Avoid using sleep in these situations while they will pause your script.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user2530266
  • 287
  • 3
  • 18
4

This is easily done with AdLibRegister passing the function name and then 1000 milliseconds (1 second).

Local $num = 0
Local $hGUI = GUICreate("Example")
Local $Pic1 = GUICtrlCreateLabel($num, 10, 10)
Local $msg
GUISetState()

AdLibRegister("addOne", 1000)

While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

Func addOne ()
    $num += 1
    GUICtrlSetData($Pic1, $num)
EndFunc
Mr. Hargrove
  • 519
  • 1
  • 6
  • 26
1

You need to set the new data in the GUI using GUICtrlSetData. Simply modify your loop like this:

While 1
   sleep(1000)
   $num += 1
   GUICtrlSetData($Pic1, $num)
WEnd

Note that I removed the double-quotes so that AutoIt handles the values as integers.

Andreas
  • 5,393
  • 9
  • 44
  • 53
  • Just for future references, autoit will automatically convert string to integer in this situation. So basically $num += "1" will work ;) It is just not a good scripting practice – user2530266 Jul 21 '14 at 22:01
  • Interesting note, thanks! Since I've thought that good practises are there for a reason I'll stick to converting strings to integers before adding them! ;) – Andreas Jul 22 '14 at 06:49