【问题标题】:Changing button background color on mouse-over event在鼠标悬停事件上更改按钮背景颜色
【发布时间】:2011-04-04 06:47:06
【问题描述】:

我正在 C# Windows 应用程序 (WinForms) 中开发一个项目,我需要创建一个函数来使用按钮鼠标悬停事件更改单个表单中所有按钮的背景颜色。我该怎么做?

【问题讨论】:

  • 您使用的是 WinForms 还是 WPF?什么是“lidos”?
  • 您需要再解释一下这个问题。按钮是否仅在您的应用程序中更改?还是您要更改其他应用的按钮?
  • 我自己在问题中明确提到,如果那是 Wpf 控件,则意味着我需要编写 Wpf 控件
  • 大声笑,是的,你现在在编辑你的问题之后,而之前的 cmets 在哪里
  • @Lawrance - Winforms 和 WPF 不一样...

标签: c# windows winforms background-color onmouseover


【解决方案1】:

更改按钮类型的所有控件:

for (int i = 0; i < Controls.Count; i++)
            if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;

钩子示例:

MouseEnter += new EventHandler(delegate(object sender, EventArgs e)
    {
        SetButtonColour(Color.Blue);
    });

MouseLeave += new EventHandler(delegate(object sender, EventArgs e)
    {
        SetButtonColour(Color.Red);
    });

public void SetButtonColour(Color colour)
    {
        for (int i = 0; i < Controls.Count; i++)
            if (Controls[i] is Button) Controls[i].BackColor = Color.Blue;
    }

【讨论】:

    【解决方案2】:

    假设您只是更改自己的应用程序,这并不难。

    在鼠标悬停事件中,只需遍历窗体的 Controls 属性,对于所有 Button 项,更改背景颜色。您可能需要编写一个递归函数来查找所有按钮,因为 Panel(或 GroupBox 等)包含其所有控件的 Controls 属性。

    【讨论】:

    • 只是这样做,所有按钮都放在组框内,我已经尝试过如下代码的文本框,但是使用鼠标悬停事件更改背景色对我来说有点关键 public static void Fungbstyle( GroupBox gbsty){ gbsty.BackColor = Color.LightSteelBlue; gbsty.Cursor = Cursors.AppStarting; foreach (在 gbsty.Controls 中控制 cnn){ if (cnn is TextBox){ cnn.BackColor = Color.LightCyan; cnn.Cursor = Cursors.PanNW; cnn.Font = new Font(cnn.Font, FontStyle.Italic); cnn.Width = 156; }}}
    【解决方案3】:

    类似这样的:

    public partial class Form1 : Form
    {
        Color defaultColor;
        Color hoverColor = Color.Orange;
    
        public Form1()
        {
            InitializeComponent();
            defaultColor = button1.BackColor;
        }
    
        private void Form1_MouseHover(object sender, EventArgs e)
        {
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is Button)
                {
                    ctrl.BackColor = hoverColor;
                }
            }
        }
    
        private void Form1_MouseLeave(object sender, EventArgs e)
        {
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is Button)
                {
                    ctrl.BackColor = defaultColor;
                }
            }
        }
    }
    

    【讨论】:

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