【问题标题】:Mouse Over Effects for Button in C# (using Visual Studio 05)C# 中按钮的鼠标悬停效果(使用 Visual Studio 05)
【发布时间】:2009-07-18 19:53:09
【问题描述】:

我想根据 mouseenter 和 mouseleave 事件更改背景图像,以实现按钮的鼠标悬停效果。实现这一点的最简单方法是什么(最好是可以继承按钮的方式)?

【问题讨论】:

    标签: c# .net visual-studio


    【解决方案1】:
    private void Form1_Leave(object sender, System.EventArgs e)
    {
    this.BackgroundImage=Image.FromFile("file1");       
    }
    
    private void Form1_MouseEnter(object sender, System.EventArgs e)
    {
    this.BackgroundImage=Image.FromFile("file2");
    }       
    

    【讨论】:

    • 非常感谢您展示了如何从文件中加载图像。我是 VC# 的新手,所以不知道如何实现。
    【解决方案2】:

    您可以创建一个新类,继承自 Button,并覆盖 OnMouseEnterOnMouseLeave。给它一个属性,这样你就可以设置当鼠标进入时它应该得到哪个背景图像,你就可以开始了。

    完整的工作示例(添加了几个设计时支持属性):

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using System.ComponentModel;
    
    namespace WindowsFormsApplication1
    {
        class HighlightButton : Button
        {
            [Category("Appearance")]
            [Description("The background image that the Button should have when the mouse is over a visible part of it.")]
            public Image MouseoverBackgroundImage { get; set; }
            // property to hold the original background image while the mouse-over
            // image is displayed, so that we can restore it when the mouse leaves
            protected Image OriginalBackgroundImage { get; set; }
    
            protected override void OnMouseEnter(EventArgs e)
            {
                this.OriginalBackgroundImage = this.BackgroundImage;
                this.BackgroundImage = this.MouseoverBackgroundImage;
                base.OnMouseEnter(e);
            }
    
            protected override void OnMouseLeave(EventArgs e)
            {
                this.BackgroundImage = this.OriginalBackgroundImage;
                base.OnMouseLeave(e);
            }
        }
    }
    

    编辑:意识到我的初始示例更改了 BackColor,而不是 BackgroundImage。解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2013-01-17
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      相关资源
      最近更新 更多