Force an area of a Window to Repaint

This sample shows how to force an area of a window to repaint. Sometimes this is necessary, particularly when you're experimenting with owner draw control techniques, or when using the LockWindowUpdate API call to improve the speed at which a control fills with data.

Create a new project, add a module and paste in the code below:

Private Type RECT 
    Left As Long 
    Top As Long 
    Right As Long 
    Bottom As Long 
End Type 
Private Type POINTAPI 
    X As Long 
    Y As Long 
End Type 
Private Declare Function GetWindowRect Lib "user32" ( _
    ByVal hWnd As Long, lpRect As RECT) As Long 
Private Declare Function GetClientRect Lib "user32" ( _
    ByVal hWnd As Long, lpRect As RECT) As Long 
Private Declare Function InvalidateRect Lib "user32" ( _
    ByVal hWnd As Long, lpRect As RECT, ByVal bErase As Long) As Long 
Private Declare Function ScreenToClient Lib "user32" ( _
    ByVal hWnd As Long, lpPoint As POINTAPI) As Long 

Public Sub RepaintWindow( _ 
        ByRef objThis As Object, _ 
        Optional ByVal bClientAreaOnly As Boolean = True _ 
Dim tR As RECT 
    If (bClientAreaOnly) Then 
        GetClientRect objThis.hWnd, tR 
        GetWindowRect objThis.hWnd, tR 
        tP.X = tR.Left: tP.Y = tR.Top 
        ScreenToClient objThis.hWnd, tP 
        tR.Left = tP.X: tR.Top = tP.Y 
        tP.X = tR.Right: tP.Y = tR.Bottom 
        ScreenToClient objThis.hWnd, tP 
        tR.Right = tP.X: tR.Bottom = tP.Y 
    End If 
    InvalidateRect objThis.hWnd, tR, 1 
End Sub 

To try out the redrawing, add a ListBox and a Command button to your Project's form. Make the ListBox as big as possible so you will see the effect. Then add the following code:

Private Sub Command1_Click() 
    RepaintWindow List1 
End Sub 

Private Sub Form_Load() 
Dim i As Long 
    For i = 1 To 200 
        List1.AddItem "TestItem " & i 
    Next i 
End Sub 

When you click on the button, the client area of the List Box will be entirely redrawn. The effect is not particularly noticeable with the List Box as shown, but basically this tip is here to get you around any problems you have when things don't redraw themselves properly.