PRB: How to Prevent Flicker in the Repaint of a Label (112675)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 3.0
  • Microsoft Visual Basic Professional Edition for Windows 3.0

This article was previously published under Q112675

SYMPTOMS

When a label control fires a change event, the Caption tends to flicker as it is repainted within the control -- more so when the font size is large.

WORKAROUND

The flicker can be avoided if a picture control (with its AutoRedraw property set to true) is used instead of the label control. However, note that a picture control uses considerably more resources than a label. If you're going to replace a lot of labels, replace them all with one picture control (and multiple print statements) rather than with multiple picture controls. Otherwise, you'll run out of system resources.

The following example demonstrates the use of the picture control to prevent the flicker.

  1. Start a new project in Visual Basic, Form1 is created by default.
  2. Add a picture box (Picture1) to the form, and set its autoredraw property to True.
  3. Add a timer control (Timer1) to the form and set its interval property to 100.
  4. Add the following code to the Timer1_Timer event:
       Sub Timer1_Timer ()
          ' Reset the picture in Picture1:
          Picture1.Cls
          ' Specify the top and left coordinates for the text:
          Picture1.CurrentX = 100
          Picture1.CurrentY = 100
          ' Enter the text (in this case the current time):
          Picture1.Print = Format$(Now, "h:mm:ss AM/PM")
       End Sub
    						
  5. Run the program.

An Alternative to the Picture Control

Flicker in a label can be reduced considerably by only updating it when absolutely necessary. For example, update it at the end by using code similar to this:
   Sub Timer1_Timer ()
      Dim TimeStr As String
      TimeStr = Format$(Now, "h:mm:ss AM/PM")
      If Label1.Caption <> TimeStr Then Label1.Caption = TimeStr
   End Sub
				
Or by using code similar to this slightly more efficient code:
   Sub Timer1_Timer ()
      Static LastSecond As Integer
      If Seconds(Now) <> LastSecond Then
         LastSecond = Seconds(Now)
         Label1.Caption = Format$(Now, "h:mm:ss AM/PM")
      End If
   End Sub
				

MORE INFORMATION

Steps to Reproduce Behavior

  1. Start a new project in Visual Basic. Form1 is created by default.
  2. Add a label control (Label1) to Form1.
  3. Add a timer control (Timer1) to Form1.
  4. Add the following code to the Timer1_Timer event:
       Sub Timer1_Timer ()
          Label1.Caption = Format$(Now, "h:mm:ss AM/PM")
       End Sub
    						
  5. Run the program.
You will notice a flicker of the caption of the label control. If you have trouble seeing the flicker, try increasing the fontsize.

Modification Type:MajorLast Reviewed:10/28/2003
Keywords:kbprb KB112675