如何使用 VB.NET 在 Windows 10 上的 Windows 窗体标题栏中绘制自定义按钮?

问题描述

我使用 VB.NET 和 Windows 窗体搜索以在窗体的标题栏中显示自定义按钮。

我已阅读并复制了 How to draw custom button in Window Titlebar with Windows Forms? Adding a custom button in title bar VB.NET代码

这 2 个问答的问题在于它们很旧,无法在我打开 Windows 10 的 PC 上运行。

当我使用以下代码

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 = System@R_275_404[email protected]
        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

当我在 Visual Studio 2019 的调试模式下运行此代码时,自定义按钮永远不会显示

enter image description here

当我像这样更改 WM_NCPAINT 代码(所有行都被注释)

Case WM_NCPAINT
            'MyBase.WndProc(m)
            'DrawButton(m.HWnd)
            'm.Result = IntPtr.Zero

我得到以下结果

enter image description here

如果我激活 VS Studio 2019 并返回到我的应用程序,我可以看到以下结果。

enter image description here

我要说明的是第一个带有红色矩形的 PrintScreen。最后一个 PrintScreen 不正确,因为 MinimizeClose 按钮具有不同的样式!

我的代码中有什么错误

感谢您的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)