更改(自定义)ProgressBar颜色

时间:2015-10-30 02:28:16

标签: .net vb.net winforms progress-bar pinvoke

我正在创建一个带有属性的自定义进度条

Public Class CustomProgressBar : Inherits ProgressBar

    Private _State As ProgressStates

    <DllImport("user32.dll", CharSet:=CharSet.Auto)> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <MarshalAs(UnmanagedType.LPWStr)> ByVal lParam As String) As Int32
    End Function

    <Category("Appearance")> _
    <DefaultValue(ProgressStates.Normal)> _
    <Description("The progress state, Red=Error, Yellow=Warning, Green=Normal")> _
    Public Property State As ProgressStates
        Get
            Return _State
        End Get
        Set(value As ProgressStates)
            _State = value
            SendMessage(MyBase.Handle, 1040, value, 0)
        End Set
    End Property

End Class

ProgressStates

Public Enum ProgressStates

    Normal = 1
    [Error] = 2
    Warning = 3

End Enum

在设计器中我将自定义属性设置为Error并且它在设计器中工作正常,但是当我运行应用程序时,进度值自动设置为0并且不应用属性

Designer and executable

1 个答案:

答案 0 :(得分:2)

它与该属性完全无关,但PInvoke在源代码或转换中并不完美。我怀疑你是从this old C# answer开始的。

Imports System.Runtime.InteropServices
Class NativeMethods
    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=False)>
    Private Shared Function SendMessage(hWnd As IntPtr,
                                        Msg As UInt32,
                                        w As IntPtr,
                                        l As IntPtr) As IntPtr
    End Function

    Private Const PBM_SETSTATE = &H400 + 16
    Friend Enum PBMStates
        Normal = 1
        [Error] = 2
        Paused = 3
    End Enum

    Friend Shared Sub SetProgressState(ctl As ProgressBar, state As PBMStates)
        SendMessage(ctl.Handle, PBM_SETSTATE, New IntPtr(state), IntPtr.Zero)
    End Sub
End Class

根据MSDN文档,PBM_SETSTATE返回先前的状态。我忽略了它并使它成为Sub。由于它只应与ProgressBar I一起使用,因此它只接受ProgressBar控件而不是控件句柄(可以来自任何控件)。最后,代码为Shared并且在NativeMethods类中,因此CA不会抱怨。用法:

NativeMethods.SetProgressState(ProgressBar1, NativeMethods.PBMStates.Error)

结果:

enter image description here