【问题标题】:Change my Winform button behavior when hover, click悬停时更改我的 Winform 按钮行为,单击
【发布时间】:2014-05-03 00:10:47
【问题描述】:

请从Telerik看一下这个实现:

悬停时:

点击时:

我可以在不使用任何 3rd 方程序的情况下实现它吗?

【问题讨论】:

  • 创建自定义控件。
  • 您能详细说明一下吗?
  • 你使用什么编程语言?
  • @Nimesh 如果你不知道什么是语言,你就不知道该怎么做。

标签: c# .net winforms button


【解决方案1】:

我创建了一个示例来演示如何创建自定义控件。

创建一个 UserControl 并命名为 Sample 并将以下代码放入 .cs 文件中。

[DefaultEvent("Click")]
public partial class Sample : UserControl
{
    private string _text;
    [Browsable(true)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public override string Text
    {
        get
        {
            return _text;
        }
        set
        {
            _text = value;
        }
    }
    private bool _mouseDown = false;
    private bool _mouseHover = false;
    private bool _invalidateRequired = true;

    public Sample()
    {
        InitializeComponent();
    }
    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);
        _mouseDown = true;
        _invalidateRequired = true;
        this.Invalidate();
    }
    protected override void OnMouseUp(MouseEventArgs e)
    {
        base.OnMouseUp(e);
        _mouseDown = false;
        _invalidateRequired = true;
        this.Invalidate();
    }
    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        _mouseHover = true;
        if (_invalidateRequired)
        {
            this.Invalidate();
            _invalidateRequired = false;
        }
    }
    protected override void OnMouseLeave(EventArgs e)
    {
        base.OnMouseLeave(e);
        _mouseHover = false;

        this.Invalidate();
        _invalidateRequired = true;
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        Rectangle r = new Rectangle(0, 0, this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1);
        Color bg = Color.White;
        Color fr = Color.Gray;
        Color br = Color.FromArgb(173, 178, 173);
        if (_mouseDown)
        {
            bg = Color.FromArgb(24, 162, 231);
            fr = Color.White;
        }
        if (_mouseHover)
            br = Color.FromArgb(24, 162, 231);
        e.Graphics.FillRectangle(new SolidBrush(bg), r);
        e.Graphics.DrawRectangle(new Pen(br, 3), r);
        StringFormat sf = new StringFormat();
        sf.LineAlignment = StringAlignment.Center;
        sf.Alignment = StringAlignment.Center;
        e.Graphics.DrawString(Text, this.Font, new SolidBrush(fr), r, sf);            
    }
}

Code with Designer.cs

【讨论】:

  • 如何处理这个类中的 InitializeComponent() ? (当前上下文中不存在名称“InitializeComponent”)
  • 如果您添加了用户控件,则无需创建 InitializeComponent,因为它已在 Designer.cs 文件中定义。确保您选择了 UserControl 而不是类。
  • 为什么将 Button FlatStyle 从 Standard 更改为 Flat 时默认颜色变为灰色?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
相关资源
最近更新 更多