这个例子告诉你如何强制窗口的一部分重画。有时这是必须的,特别是当你试验自己重画控件的技术,或者已经使用了LockWindowUpdate
这个API函数以阻止控件重画时(参见“防止一个窗口重画”)。
新建一个项目,添加一个module,然后粘贴下列代码:
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
Dim tP As POINTAPI
If (bClientAreaOnly) Then
GetClientRect objThis.hWnd, tR
Else
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
为了试试重画,在窗体上添加一个ListBox和一个Command。把ListBox拉得大一些,这样效果比较明显。再加入下列代码:
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
当你单击Command按钮,ListBox的客户区将全部重画。对于ListBox,这种效果并不十分明显地显示,但这段代码放在这里主要目的,是让你在
遇上有东西不能恰当地重画它自己时可以有办法解决。
——————————————————————————————————————————————
防止窗口重画 WXJ_Lake 编译
这则代码演示了如何防止窗口的一部分重画。当你要往ListBox或ListView这样的控件里添加许多项时,暂缓重画可以相当地提高处理速度。
在我的系统上,往一个ListBox中加10000项比原来提速30%
新建一个项目,添加一个ListBox、一个Command和一个CheckBox。把CheckBox的Caption设为"&Lock Update",Command的Caption设为"&Load"。
然后,把下列代码粘贴到窗体中:
Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Long) As Long
Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Private Sub Command1_Click()
Dim i As Long
Dim lTIme As Long
lTIme = timeGetTime()
If (Check1.Value = Checked) Then
LockWindowUpdate List1.hWnd
End If
List1.Clear
For i = 1 To 10000
List1.AddItem "Test " & i
Next i
If (Check1.Value = Checked) Then
LockWindowUpdate 0
List1.Refresh
End If
MsgBox "Time: " & timeGetTime - lTIme
End Sub
当你单击Command按钮,代码将往ListBox中添加10000项。如果"Lock Update"的复选框被选中,Windows将在往ListBox中添加项时防止它的重画。操作结束后,会弹出一个对话框报告运行时间。
- 还没有人评论,欢迎说说您的想法!