Timer - Sub as Event Handler

From Liberty BASIC Family
Jump to navigation Jump to search


Description

Using a sub as the event handler for the TIMER command causes the program to hang, if the window is moved or resized. Sometimes, the only way to exit is to use either the Task Manager or CTRL+Break. Either method will cause the LB IDE to crash.

Example code to demonstrate the bug.

You will need to use Ctrl+Break to exit the program after attempting to move or resize the window.

    WindowWidth = 400
    WindowHeight = 300
    msg1$ = "Drag this window around or resize with your mouse."
    msg2$ = "Do it again."
    msg3$ = time$()
    msg4$ = "Press Ctrl-Break to End Program"
    statictext #demo.m1, msg1$, 20, 50, 350, 50
    statictext #demo.m2, msg2$, 20, 100, 350, 50
    statictext #demo.m3, msg3$, 20, 150, 350, 50
    statictext #demo.m4, msg4$, 20, 200, 350, 50
    open "Timer Using a Sub as Event Handler" for window as #demo
    #demo "trapclose quit"
    #demo "font verdana 12"
    timer 250, updateTime
wait

sub quit handle$
    timer 0
    close #handle$
  end
end sub

sub updateTime
    #demo.m3 time$()
end sub

Example code to work around the bug.

Using a branch label for the timer event handler does not cause a problem.

    WindowWidth = 400
    WindowHeight = 300
    msg1$ = "Drag this window around or resize with your mouse."
    msg2$ = "Do it again."
    msg3$ = time$()
    msg4$ = "Using a branch label as event handler works well."
    statictext #demo.m1, msg1$, 20, 50, 350, 50
    statictext #demo.m2, msg2$, 20, 100, 350, 50
    statictext #demo.m3, msg3$, 20, 150, 350, 50
    statictext #demo.m4, msg4$, 20, 200, 350, 50
    open "Timer Using Branch Label as Event Handler" for window as #demo
    #demo "trapclose [quit]"
    #demo "font verdana 12"
    timer 250, [updateTime]
wait

[quit]
    timer 0
    close #demo
end

[updateTime]
    #demo.m3 time$()
wait

You cannot generally mix Subs and [branchLabel] event handlers, if you are coding ALL Subs it is possible to ENCASE the timer inside a Sub.

    nomainwin
    WindowWidth = 500
    WindowHeight = 300
    UpperLeftX = 0
    UpperLeftY = 0

    button #1.b1, "Press Me", buttonOneHandler, LR, 200, 10
    button #1.b2, "Press Me", buttonTwoHandler, LR, 50, 10
    textbox #1.tb, 20,20,200,20
    open "Demo" for window as #1
    #1 "trapclose quit"

    global count
    while 1
        scan
        call countUp
    wend

    sub countUp
        count=count+1
        #1.tb "Count is now ";count
        timer 500,[delay]
        wait
        [delay]
        timer 0
    end sub

    Sub buttonOneHandler handle$
        #1.tb "You pressed button one"
    end sub

    sub buttonTwoHandler handle$
        #1.tb "You pressed button two"
    end sub

    sub quit handle$
        timer 0
        close #1
        end
    end sub