C# 窗体按钮填充

C# Form Button Padding

在 C# 窗体中,我正在尝试制作漂亮的按钮,但我无法克服文本 "padding" 问题。

Problematic Button

Desired Button

我已经想好了它应该是什么样子,但我就是做不到。 它应该是带有黑色边框和 "Options" 文本的平面按钮(如第二张图片)。 但是某种 "padding" 隐藏了很大一部分文本。

更改字体大小有点帮助,但我想保留 Button 的 ~16px 高度和小字体以便它可以适应那里只是不可读。

我已经尝试将 Button 的 Padding 属性 设置为 0。 我已经在考虑一些解决方法,比如覆盖 OnPaint 事件/制作多个控件(比如,将它与标签结合起来),但我担心性能影响。

嗯,我试了一下,这是我能做的最好的了。

我使用了带有平面按钮的图像,边框提供了黑色边框之外的灰色区域。一种解决方法。随便。

这是按钮背景图像

按钮代码:

// 
// button1
// 
this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.button1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("button1.BackgroundImage")));
this.button1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.button1.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.button1.FlatAppearance.BorderSize = 4;
this.button1.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Silver;
this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Verdana", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.ForeColor = System.Drawing.Color.White;
this.button1.ImageAlign = System.Drawing.ContentAlignment.TopCenter;
this.button1.Location = new System.Drawing.Point(94, 124);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(61, 28);
this.button1.TabIndex = 0;
this.button1.Text = "Options";
this.button1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.button1.UseVisualStyleBackColor = false;

所以我用

解决了它
class FixedButton : Button {
    public string FixedText;
    public Point TextOffset;
    /*public PointF FixedTextLocation {
        get{return new PointF( (float)(Location.X+TextOffset.X), (float)(Location.Y+TextOffset.Y) );}
    }*/

    protected override void OnPaint(PaintEventArgs e){
        base.OnPaint(e);

        if(String.IsNullOrEmpty(Text) && !String.IsNullOrEmpty(FixedText) ){
            e.Graphics.DrawString(FixedText, Font, new SolidBrush(ForeColor), TextOffset);
        }
    }
}

编辑:我发现我需要在 DrawString / DrawText 中使用 TextOffset 而不是 FixedTextLocation(也可以用来代替 DrawString)。