Hi Phil,
Thank you for your reply!
Also any control that redraws itself (e.g. a button when you hover over
with the mouse) will draw itself over the text.
We can solve this problem by handling the child control's Invalidated event
and draw the text on the screen again.
Another problem is if there is another window partly obscuring the form,
the text can still get written over the top of this other window.
I think we could redraw the text in the Activated event handler of the
form.
The following is the modified sample code.
Public Class Form1
Declare Auto Function GetDC Lib "user32.dll" (ByVal hwnd As IntPtr) As
IntPtr
Declare Auto Function ReleaseDC Lib "user32.dll" (ByVal hwnd As IntPtr,
ByVal hdc As IntPtr) As Integer
Private showFnt As Font
Private showText As String
Private showPt As Point
Private invalidateChildControls As New List(Of Control)
Private textRect As New Rectangle
Private Sub Form1_Activated(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Activated
If (showText <"") Then
DrawText(showText, showFnt, showPt)
End If
End Sub
Private Function GetChildControls(ByVal rect As Rectangle) As List(Of
Control)
Dim ctrls As New List(Of Control)
For Each ctrl As Control In Me.Controls
Dim result As Rectangle = Rectangle.Intersect(ctrl.Bounds, rect)
If (Not result.IsEmpty) Then
ctrls.Add(ctrl)
End If
Next
Return ctrls
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DrawText("hello world", Me.Font, New Point(30, 50))
End Sub
Private Sub DrawText(ByVal text As String, ByVal fnt As Font, ByVal pt
As Point)
Me.Refresh()
If (showText = "") Then
Dim textSize As Size = TextRenderer.MeasureText(text, fnt)
textRect.X = pt.X
textRect.Y = pt.Y
textRect.Width = textSize.Width
textRect.Height = textSize.Height
showText = text
showFnt = fnt
showPt = pt
invalidateChildControls = GetChildControls(textRect)
For Each ctrl As Control In invalidateChildControls
AddHandler ctrl.Invalidated, AddressOf
ChildControlInvalidated
Next
End If
Dim hScreenDC As IntPtr = GetDC(IntPtr.Zero)
Dim g As Graphics = Graphics.FromHdc(hScreenDC)
Using (g)
Dim screenPt As Point = Me.PointToScreen(pt)
g.DrawString(text, Me.Font, Brushes.Red, screenPt.X, screenPt.Y)
End Using
ReleaseDC(IntPtr.Zero, hScreenDC)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
showText = ""
For Each ctrl As Control In invalidateChildControls
RemoveHandler ctrl.Invalidated, AddressOf
ChildControlInvalidated
Next
invalidateChildControls.Clear()
Me.Refresh()
End Sub
Private Sub ChildControlInvalidated(ByVal sender As Object, ByVal e As
System.Windows.Forms.InvalidateEventArgs)
If (showText <"") Then
DrawText(showText, showFnt, showPt)
End If
End Sub
End Class
Hope it is what you want.
Sincerely,
Linda Liu
Microsoft Online Community Support