@Bryan - 由@Henk魯和@chiper提出了兩種解決方案是不完美的。首先生成沒有任何視覺屬性的按鈕,然後迫使我們添加新的屬性,如OwnerDrawText
。
查看我的建議如下。我覆蓋Text
屬性以便能夠使用其專用部分_Text
並在MyBase.OnPaint(e)
事件之前附加String.Empty
。這使得該按鈕繪製時沒有文字。後來我重新將舊文本重新分配給私有屬性並自己繪製字符串。我將Inflate
添加到Rectangle
以使文本更好地觸摸按鈕的邊框,而不是重疊它。我的建議適用於任何flatstyle
。
Here is comparison of standard and no padding button in two flatstyles: standard and flat
Imports System.ComponentModel
Imports System.Drawing
Imports System.Windows.Forms
Public Class ButtonNoPadding
Inherits Button
Private _textCurrent As String
Private _Text As String
<Category("Appearance")>
Public Overrides Property Text() As String
Get
Return _Text
End Get
Set(ByVal value As String)
If value <> _Text Then
_Text = value
Invalidate()
End If
End Set
End Property
Protected Overrides Sub OnPaint(e As PaintEventArgs)
_textCurrent = Text
_Text = String.Empty
MyBase.OnPaint(e)
_Text = _textCurrent
Using brush = New SolidBrush(ForeColor)
Using stringFormat = New StringFormat() With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center}
e.Graphics.DrawString(Text, Font, brush, Rectangle.Inflate(ClientRectangle, -2, -2), stringFormat)
End Using
End Using
End Sub
End Class
C#版本:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
public class ButtonNoPadding : Button
{
private string _textCurrent;
private string _Text;
[Category("Appearance")]
public override string Text {
get { return _Text; }
set {
if (value != _Text) {
_Text = value;
Invalidate();
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
_textCurrent = Text;
_Text = string.Empty;
base.OnPaint(e);
_Text = _textCurrent;
using (brush == new SolidBrush(ForeColor)) {
using (stringFormat == new StringFormat {Alignment = StringAlignment.Center,LineAlignment = StringAlignment.Center}) {
e.Graphics.DrawString(Text, Font, brush, Rectangle.Inflate(ClientRectangle, -2, -2), stringFormat);
}
}
}
}
這將是我的首選方法,但它並不那麼簡單,因爲現有的繪畫事件將處理文本在邊界內的包裝和定位,所以我不喜歡走這條路,除非有什麼簡單的方法來實現這個目標? – Bryan 2011-05-24 09:05:58
接受,因爲Graphics.DrawString確實使文本換行和定位變得容易。完美的作品,非常感謝。 – Bryan 2011-05-24 09:21:38
酷,比我的建議更簡單,它聽起來像它的作品。 +1 – Jodrell 2011-05-24 09:29:08