Public Class TransparentTextBox
Inherits TextBox
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
End Function
Public Enum Win32
WM_PAINT = &HF
WM_PRINT = &H317
WM_HSCROLL = &H114
WM_VSCROLL = &H115
PRF_CLIENT = &H4
PRF_ERASEBKGND = &H8
End Enum
Private pictureBox As New PictureBox()
Public Sub New()
pictureBox.Dock = DockStyle.Fill
Me.Controls.Add(pictureBox)
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
Select Case m.Msg
Case Win32.WM_PAINT
Dim bmpCaptured As New Bitmap(Me.ClientRectangle.Width, Me.ClientRectangle.Height)
Dim bmpResult As New Bitmap(Me.ClientRectangle.Width, Me.ClientRectangle.Height)
Dim r As New Rectangle(0, 0, Me.ClientRectangle.Width, Me.ClientRectangle.Height)
CaptureWindow(Me, bmpCaptured)
Me.SetStyle(ControlStyles.SupportsTransparentBackColor, True)
Me.BackColor = Color.Transparent
Dim imgAttrib As New ImageAttributes()
Dim colorMap As ColorMap() = New ColorMap(0) {}
colorMap(0) = New ColorMap()
colorMap(0).OldColor = Color.White
colorMap(0).NewColor = Color.Transparent
imgAttrib.SetRemapTable(colorMap)
Dim g As Graphics = Graphics.FromImage(bmpResult)
g.DrawImage(bmpCaptured, r, 0, 0, Me.ClientRectangle.Width, Me.ClientRectangle.Height, _
GraphicsUnit.Pixel, imgAttrib)
g.Dispose()
pictureBox.Image = DirectCast(bmpResult.Clone(), Image)
Exit Select
Case Win32.WM_HSCROLL, Win32.WM_VSCROLL
Me.Invalidate()
' repaint
' if you use scrolling then add these two case statements
Exit Select
End Select
End Sub
Private Shared Sub CaptureWindow(ByVal control As Control, ByRef bitmap As Bitmap)
Dim g As Graphics = Graphics.FromImage(bitmap)
Dim i As Integer = CInt(Win32.PRF_CLIENT Or Win32.PRF_ERASEBKGND)
Dim iPtr As New IntPtr(14)
Dim hdc As IntPtr = g.GetHdc()
SendMessage(control.Handle, Win32.WM_PRINT, hdc, iPtr)
g.ReleaseHdc(hdc)
g.Dispose()
End Sub
End Class