我需要制作一个垂直和水平对齐的多行标签,但我不知道该怎么做!
我找到了一种使用此功能制作任何控制多线的方法:
private const int BS_MULTILINE = 0x00002000;
private const int BS_CENTER = 0x00000300;
private const int BS_VCENTER = 0x00000C00;
private const int GWL_STYLE = -16;
[DllImport("coredll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("coredll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
public static void MakeControlMultiline(Control control) {
IntPtr hwnd = control.Handle;
int currentStyle = GetWindowLong(hwnd, GWL_STYLE);
int newStyle = SetWindowLong(hwnd, GWL_STYLE, currentStyle | /*BS_CENTER | BS_VCENTER | */BS_MULTILINE);
}
“BS_CENTER | BS_VCENTER”在评论中,因为它不起作用!
因此,我尝试制作一个 customControl 来实现两种对齐方式,如下所示:
public partial class ImproveLabel : Control {
...
protected override void OnPaint(PaintEventArgs pe) {
Graphics g = pe.Graphics;
// text
StringFormat drawFormat = new StringFormat();
drawFormat.Alignment = StringAlignment.Center;
drawFormat.LineAlignment = StringAlignment.Center;
g.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), new Rectangle(0, 0, this.Width, this.Height), drawFormat);
// Calling the base class OnPaint
base.OnPaint(pe);
}
这里奇怪的是,如果我将两个对齐都放在“中心”,多线不再起作用,但如果只有垂直对齐到“中心”,水平对齐到“近”,多线就可以了。
我不明白为什么它会这样工作,但我需要帮助来弄清楚如何让这 3 个属性同时工作!