悬停时更改我的Winform按钮行为,单击

时间:2014-03-25 09:04:08

标签: c# .net winforms button

请从Telerik

查看此实施

enter image description here

悬停时:

enter image description here

点击:

enter image description here

我可以在不使用任何第三方程序的情况下实施吗?

1 个答案:

答案 0 :(得分:0)

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

创建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