定製化按鈕 圖片背景+ 文字

C# Forms - Buttons with multiple texts, and image

https://stackoverflow.com/questions/18192556/c-sharp-forms-buttons-with-multiple-texts-and-image

public class XButton : Button
{
    public XButton()
    {
        UseVisualStyleBackColor = false;
        TextImageRelation = TextImageRelation.ImageAboveText;
    }
    public override string Text
    {
        get { return ""; }
        set { base.Text = value;}
    }
    public string LeftText { get; set; }
    public string RightText { get; set; }
    protected override void OnPaint(PaintEventArgs pevent)
    {            
        base.OnPaint(pevent);
        Rectangle rect = ClientRectangle;
        rect.Inflate(-5, -5);
        using (StringFormat sf = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far })
        {
            using (Brush brush = new SolidBrush(ForeColor))
            {
                pevent.Graphics.DrawString(LeftText, Font, brush, rect, sf);
                sf.Alignment = StringAlignment.Far;
                pevent.Graphics.DrawString(RightText, Font, brush, rect, sf);
            }
        }
    }
}
//Use it
xButton1.Image = yourImage;
xButton1.LeftText = "How interesting winforms is";
xButton2.RightText = "F12";
//You can add more properties to this XButton class to control how it looks

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章