I search to display a custom Button in Form's Titlebar using VB.NET and Windows Forms.
I have read and copied code from How to draw custom button in Window Titlebar with Windows Forms? and Adding a custom button in title bar VB.NET
The problem with these 2 Q&A is that they are very old and don't work on my PC that turns on Windows 10.
When I use following code
Public Class Form1
Private Const WM_PAINT As Integer = &HF
Private Const WM_NCPAINT As Integer = &H85
Private Const WM_ACTIVATE As Integer = &H86
Private oButtonState = ButtonState.Normal
Private oButtonPos = New Rectangle()
Declare Function GetWindowDC Lib "user32" (ByVal hwnd As IntPtr) As IntPtr
Declare Function GetWindowRect Lib "user32" (ByVal hWnd As IntPtr, ByRef lpRect As Rectangle) As Boolean
Declare Function ReleaseDC Lib "user32" (ByVal hWnd As IntPtr, ByVal prmlngHDc As IntPtr) As <Runtime.InteropServices.MarshalAs(Runtime.InteropServices.UnmanagedType.Bool)> Boolean
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Dim x As Integer
Dim y As Integer
Dim wRect As Rectangle = New Rectangle()
Select Case m.Msg
Case WM_NCPAINT
MyBase.WndProc(m)
DrawButton(m.HWnd)
m.Result = IntPtr.Zero
Case WM_PAINT
MyBase.WndProc(m)
DrawButton(m.HWnd)
m.Result = IntPtr.Zero
Case WM_ACTIVATE
MyBase.WndProc(m)
DrawButton(m.HWnd)
Case Else
MyBase.WndProc(m)
End Select
End Sub
Private Sub DrawButton(hwnd As IntPtr)
Dim hDC = GetWindowDC(hwnd)
Dim x As Integer
Dim y As Integer
Using g As Graphics = Graphics.FromHdc(hDC)
Dim iCaptionHeight = Bounds.Height - Me.ClientRectangle.Height
Dim oButtonSize As Size = SystemInformation.CaptionButtonSize
x = Bounds.Width - 4 * oButtonSize.Width
y = (iCaptionHeight - oButtonSize.Height) / 2
oButtonPos.Location = New Point(x, y)
'// Work out color
Dim color As Brush
If oButtonState = ButtonState.Pushed Then
color = Brushes.LightGreen
Else
color = Brushes.Red
End If
'// Draw our "button"
g.FillRectangle(color, x, y, oButtonSize.Width, oButtonSize.Height)
End Using
ReleaseDC(hwnd, hDC)
End Sub
End Class
When I run this code in debug mode from Visual Studio 2019, custom button is never displayed !
When I change WM_NCPAINT code (all lines are commented) like this
Case WM_NCPAINT
'MyBase.WndProc(m)
'DrawButton(m.HWnd)
'm.Result = IntPtr.Zero
I obtain following result
If I activate VS Studio 2019 and I go back to my application, I can see following result.
What I'm expexting is first PrintScreen with red rectangle. Last PrintScreen is not correct because Minimize
and Close
buttons have a distinct style !
What is false in my code ?
Thanks for any help.