devxlogo

Don’t stop timers when a MsgBox is active

Don’t stop timers when a MsgBox is active

Not all developers know that Timer controls in compiled VB5 and VB6 applications aren’t stopped by MsgBox statement, so the Timer’s Timer event procedure is regularly executed even when the message box is being displayed on the screen.

However, inside interpreted applications under all VB versions, Timers are stopped when a MsgBox is active, which means that, if you rely on the code in the Timer event procedure, you can’t completely test and debug your app withing the VB environment.

To do so, you must use the MessageBox API function instead of the built-in MsgBox function. The API function has a similar syntax, but it takes an additional argument that states the parent window of the message box dialog (you can use Me.hWnd), and the order of the Title and Buttons arguments is reversed. Even more interesting, all the VB constants can be used without any problem for the Buttons argument:

Private Declare Function MessageBox Lib "user32" Alias "MessageBoxA" (ByVal _    hWnd As Long, ByVal lpText As String, ByVal lpCaption As String, _    ByVal wType As Long) As Long

To test this function, create a new form and place one timer, one label, and two command buttons on its surface, then type this code:

Private Sub Command1_Click()    MsgBox "The Timer STOPS!", vbOKOnly, "Regular MsgBox"End SubPrivate Sub Command2_Click()    MessageBox Me.hWnd, "The Timer DOESN'T STOP", "MessageBox API function", _        vbOKOnly + vbExclamationEnd SubPrivate Sub Timer1_Timer()Label1.Caption = TimeEnd Sub

Even better, you can wrap the API function into a MsgBox-like function that takes the same arguments in the same order:

Function MsgBox2(Prompt As String, Optional Buttons As VbMsgBoxStyle, _    Optional Title As Variant) As VbMsgBoxResult    If IsMissing(Title) Then Title = App.Title    MsgBox2 = MessageBox(Screen.ActiveForm.hWnd, Prompt, Title, Buttons)End Function

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist