namespace SkyCtl { using System; using System.Windows.Forms; // 可调整标签文本对齐方式的群组框 public class GroupBox : System.Windows.Forms.GroupBox { // 标签文本 Label lbl; // 标签文本对齐方式 HorizontalAlignment textAlign = HorizontalAlignment.Left; // 构造函数 public GroupBox() { lbl = new Label(); lbl.Parent = this; lbl.AutoSize = true; SetLabelLocation(); } // 公有属性:标签文本对齐方式 public HorizontalAlignment TextAlign { get { return textAlign; } set { textAlign = value; SetLabelLocation(); } } // 重写公有属性:文本 public new string Text { get { return lbl.Text; } set { lbl.Text = value; SetLabelLocation(); } } // 重写调整控件大小方法 protected override void OnResize(EventArgs e) { base.OnResize(e); SetLabelLocation(); } // 定位标签位置 void SetLabelLocation() { lbl.Left = textAlign == HorizontalAlignment.Left ? 6 : textAlign == HorizontalAlignment.Center ? (Width - lbl.Width) / 2 : Width - lbl.Width - 6; } } } namespace Test { using System; using System.Windows.Forms; using GroupBox = SkyCtl.GroupBox; // 测试:可调整标签文本对齐方式的群组框 class Form1 : Form { GroupBox grp1, grp2; Form1() { Text = "可调整标签文本对齐方式的群组框"; grp1 = new GroupBox(); grp1.Parent = this; grp1.Text = "GroupBox1"; grp1.TextAlign = HorizontalAlignment.Right; grp1.Dock = DockStyle.Fill; grp2 = new GroupBox(); grp2.Parent = this; grp2.Text = "GroupBox2"; grp2.TextAlign = HorizontalAlignment.Center; grp2.Width = Width / 2; grp2.Dock = DockStyle.Right; } protected override void OnResize(EventArgs e) { base.OnResize(e); grp2.Width = Width / 2; } static void Main() { Application.Run(new Form1()); } } }