【问题标题】:button backcolor is lost when mouse not hovering over鼠标未悬停时按钮背景色丢失
【发布时间】:2010-08-14 20:24:26
【问题描述】:

我的框架上有许多按钮,我想通过显示背景颜色来显示选择了哪个按钮。唯一的问题是,这个背景色只有在鼠标悬停在按钮上时才可见,否则按钮将是纯白色。

覆盖 MouseEnter 和 MouseLeave 事件没有帮助。

该按钮继承自标准 Windows 窗体按钮,并具有以下方法来显示它是否被选中:

public void SetFocus(bool focused)
{
    if (focused)
        this.BackColor = SelectColor;
    else this.BackColor = color;
}

SelectColor 是一种静态黄色(表示按钮已被选中),color 是存储在类中的私有颜色,该类保存按钮未选中时的颜色。

有谁知道如何显示背景颜色,即使没有将鼠标悬停在按钮上?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    创建一个从Button派生的新类:

    class MyButton : Button
    {
        public MyButton() : base()
        {
            this.BackColor = System.Drawing.Color.AntiqueWhite;
        }
    
        protected override void OnMouseEnter(EventArgs e)
        {
            this.BackColor = System.Drawing.Color.Blue;
            base.OnEnter(e);
        }
    
        protected override void OnMouseLeave(EventArgs e)
        {
            this.BackColor = System.Drawing.Color.AntiqueWhite;
            base.OnLeave(e);
        }
    }
    

    然后在表单上使用它对我有用。您要么必须以编程方式添加按钮,要么编辑 .designer.cs 文件。

    显然用你的值替换我的硬编码颜色。

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 2011-04-04
      相关资源
      最近更新 更多