禁用时保持按钮前景色

问题描述 投票:0回答:1

我在winform应用程序中有一个按钮。问题是当我禁用该按钮时,原色变成绿色。即使禁用它,有没有办法保持原色为黑色???我从过去的SO问题中尝试了许多解决方案,现在花了一段时间搜索谷歌,但是这些解决方案要么是用c#(我将它们转换了但还算不上运气),或者创建了一个自定义按钮控件。有解决方案吗?

vb.net button disabled-control
1个回答
0
投票

我有一个类似的问题。按钮没有执行.ForColor分配的原因(如果我没记错的话)与正在重绘和重绘它的背景事件有关。我还没有完全了解“坚韧不拔”,但要点是(到目前为止,我发现)解决颜色的唯一方法是在绘画事件中。

基本上,您可以处理扩展程序中的颜色更改,而使用Button.Enabled = False则可以这样称呼它:

btnNext.Enable
btnPrevious.Disable

您需要做的就是在您的项目中添加一个模块(在下面),所有按钮将具有.Enable.Disable扩展名。

HERE'S MODULE

Module Extensions
    <System.Runtime.CompilerServices.Extension()>
    Public Sub Enable(ByVal btn As Button)
        btn.Enabled = True
    End Sub

    <System.Runtime.CompilerServices.Extension()>
    Public Sub Disable(ByVal btn As Button)
        AddHandler btn.EnabledChanged, AddressOf btn_EnabledChanged
        AddHandler btn.Paint, AddressOf btn_Paint
        btn.Enabled = False
    End Sub

    Private Sub btn_EnabledChanged(sender As Object, e As System.EventArgs)
        Dim btn As Button = DirectCast(sender, Button)
        If sender.enabled = False Then
            btn.ForeColor = Color.Black
        Else
            btn.ForeColor = Color.Black
        End If
    End Sub

    Private Sub btn_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs)
        'Dim TextForBtn As String = ""  ' << we don't use a variable because that would only be useful if we could reassign to the .Text property, but that just raises the Paint Event again causing a infinite loop.
        Dim btn As Button = DirectCast(sender, Button)
        If btn.Text > " " Then
            btn.Tag = btn.Text ' << this allows us to redraw the text, the one issue however is the .Text property is empty from here on out.
            'TextForBtn = btn.Text ' << this is part of the failed idea of using a variable and reassigning to the .Text property.
        End If
        btn.Text = String.Empty ' << make sure Text is not written on button as well as rendered below
        Dim flags As TextFormatFlags = TextFormatFlags.HorizontalCenter Or TextFormatFlags.VerticalCenter Or TextFormatFlags.WordBreak  'center the text
        TextRenderer.DrawText(e.Graphics, btn.Tag.ToString, btn.Font, e.ClipRectangle, btn.ForeColor, flags) ' << TextForBtn was replaced with btn.Tag.ToString in the second parameter
        'btn.Text = TextForBtn ' << this caused an infinite loop necessitating the use of the .Tag property.
    End Sub
End Module
© www.soinside.com 2019 - 2024. All rights reserved.