禁用按钮上的实际文本颜色

3
VB2012:我正在创建一个按钮控件,并继承自.NET按钮。从这里https://blogs.msdn.microsoft.com/jfoscoding/2005/11/10/building-a-splitbutton/启用基本功能。由于我正在重新绘制按钮,因此必须引入一些代码来更改禁用时的按钮文本。

所以根据过去的经验,我立即使用了SystemColors.GrayText。但与普通的.NET按钮相比,禁用时的颜色似乎有点不对劲。经过尝试,最接近的是SystemColors.ControlDark。我找不到这个任何文档中的说明。我是否做得正确?


FYI,CodeProject 上大约有十几个分割按钮。 - Ňɏssa Pøngjǣrdenlarp
https://dev59.com/v2sz5IYBdhLWcg3wn5Xa - Ňɏssa Pøngjǣrdenlarp
是的,我知道。它们没有做我想要的事情,有些只是过度设计了。这个正是我所需要的,而且我可以在添加东西的同时学习。 - sinDizzy
非常感谢。我也读了那篇SO文章,但它没有说明为什么会这样。在我的情况下,我正在运行带有Windows Classic的Win7,因此假设GrayText会起作用,但是并没有成功。 - sinDizzy
如果您要重新绘制整个按钮,则必须自己完成...对吗? - sinDizzy
2个回答

1

在编写了一个非常笨重的像素查看程序之后,似乎前景色是160,160,160,背景色是204,204,204。Windows ClearType字体平滑使事情有点困难,生活从来不简单啊?

因此,您需要设置颜色类似于这样

    Me.ForeColor = Color.FromArgb(160, 160, 160)
    Me.BackColor = Color.FromArgb(204, 204, 204)

或者至少在我的 Windows 10 电脑上使用标准主题时是这样的。


0
对于这样的问题,参考源是你的好朋友。如果你跟踪调用链,你会发现System.Windows.Forms.Button类最终调用ButtonBaseAdapter.DrawText方法来在按钮上实际绘制文本。调用栈看起来像这样:
  • System.Windows.Forms.ButtonBase.OnPaint
  • System.Windows.Forms.ButtonBase.PaintControl
    • PaintControl 方法调用 Adapter.PaintAdapter 是一个属性,它返回当前按钮的绘图适配器。返回的适配器取决于样式(即平面、弹出、标准)。如果是标准样式按钮,则调用 Button.CreateStandardAdapter 方法,该方法返回一个 ButtonStandardAdapter,因此 PaintControl 方法将使用它。但是,ButtonStandardAdapter.Paint 方法是由其基类实现的,因此会调用它。
  • System.Windows.Forms.ButtonInternal.ButtonBaseAdapter.Paint
  • System.Windows.Forms.ButtonInternal.ButtonStandardAdapter.PaintUp
  • System.Windows.Forms.ButtonInternal.ButtonStandardAdapter.PaintWorker
  • System.Windows.Forms.ButtonInternal.ButtonBaseAdapter.PaintField
  • System.Windows.Forms.ButtonInternal.ButtonBaseAdapter.DrawText
在那个DrawText方法中,你会看到它像这样绘制禁用文本:
if (disabledText3D && !Control.Enabled) {
    r.Offset(1, 1);
    using (SolidBrush brush = new SolidBrush(colors.highlight)) {
        g.DrawString(Control.Text, Control.Font, brush, r, stringFormat);
        r.Offset(-1, -1);
        brush.Color = colors.buttonShadow;
        g.DrawString(Control.Text, Control.Font, brush, r, stringFormat);
    }
}

首先,它使用colors.highlight在偏移量为(1, 1)的位置绘制文本,然后再次绘制文本,但这次使用colors.buttonShadow在偏移量为(-1, -1)的位置。变量colors是对ColorData对象的引用。如果您跟随代码,您会发现ColorData是由System.Windows.Forms.ButtonInternal.ButtonBaseAdapter.ColorOptions.Calculate方法创建的。它返回的颜色取决于一些系统设置,例如普通模式与高对比度模式。但是,在标准情况下,它返回的颜色似乎是:

ColorData.highlight = SystemColors.ControlLightLight
ColorData.buttonShadow = SystemColors.ControlDark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接