SpringButton

介绍 这个示例展示了如何构建一个具有良好图形界面的简单按钮。此控件是使用绘图类和essential关键字的示例。我决定画一个不寻常的按钮,如下图所示: 第一步 首先,我声明我的新类:

public class SpringButton : Control
{}

如何暴露礼仪 在那之后,我展示了一些基本的属性,比如三角形的像素大小和按钮的第二种颜色。我需要的其他礼节都可以在系统。窗口。表格中找到。控制类。

//this variable say if the
//mouse is over the contol
private bool Sel = false;
private Color BackColor2= Color.Gray;

public Color BackColorEnd
{
    get{return BackColor2; }
    set{BackColor2=value; 
        this.Invalidate();  }
}

int _triangle =25;
//I add a proprety
//that's the lenght of
//a triangle rectangle (45°)

public int Triangle
{
    get{return _triangle;}
    set{ 
        _triangle=value;
        //if lenght change I update 
        //the control
        this.Invalidate(true);
    }
}

鼠标“照明” 另一个重要的步骤是当鼠标在控件上时将其设置为“selected”。因此,如果鼠标在控件上,背景颜色和边框颜色就会颠倒过来(参见OnPaint覆盖中的代码)。

//set the button as "selected" on mouse entering
//and as not selected on mouse leaving
protected override void OnMouseEnter(EventArgs e)
{
    Sel = true;
    this.Invalidate();
}
protected override void OnMouseLeave(EventArgs e)
{
    Sel = false;
    this.Invalidate();
}

的核心 主要步骤是重写OnPaint过程。在这种方法中,我直接在控件上作画。首先是中间的矩形,然后是对角的两个三角形。这是代码:

protected void PaintBut(PaintEventArgs e)
{
    //I select the rights color 
    //To paint the button...
    Color FColor = this.BackColorEnd;
    Color BColor = this.BackColor;
    if (Sel == true)
    {
      FColor = this.BackColor;
      BColor = this.BackColorEnd;
    }
    //and draw(see All the code...)

委托 现在我将解释如何使用委托。我声明了这个类,用作EventArgs。当用户点击控件时,如果点击是在一个三角形上,我委托TriangleEventArgs说这个三角形被点击了。

protected override void OnMouseDown(MouseEventArgs e)
{ 
    base.OnClick(e);
    // if the user use this delegate...
    if (this.TriangleClick != null)
    {
    //check if the user click on the left triangle
    //or in the right with some geometrics  rules...
    //(is't possible to click all triangle at the same time )
    
    int x= e.X;
    int y= e.Y;
    
    if((x<_triangle)&&(y<=(_triangle-x))||
       (x>this.ClientRectangle.Width-_triangle)&&
       (y>=(this.ClientRectangle.Height-_triangle-x)) )
    {
        //try with right...
        TriangleClickEventArgs te= new TriangleClickEventArgs(false);
        //if not...
        if((x<_triangle)&&(y<=(_triangle-x)))
            te= new TriangleClickEventArgs(true);
           
            this.TriangleClick(this,te);
        }
    }
}

学分 如果你想看我的其他作品,请访问我的主页:http://zeppaman.altervista.org。 本文转载于:http://www.diyabc.com/frontweb/news460.html

原文地址:https://www.cnblogs.com/Dincat/p/13450163.html