I need to make a multiline label with vertical and horizontal alignment and I don't know how I can do it !
I have found a way to make any control multiline with this function :
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);
}
The "BS_CENTER | BS_VCENTER" is in comment since it doesn't work !
So I try to make a customControl where I realise both alignments, like this :
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);
}
The strange thing here is that if I put both alignements to "Center", the multiline doesn't work anymore but if there is only the vertical alignment to "Center" and the horizontal alignment to "near", the multiline works.
I don't understand why it works this way but I need help to figure how I can get the 3 attributes working at the same time !
The code below is straight out of the P/Invoke SetWindowLong example.
private const int GWL_STYLE = -16;
private const int BS_CENTER = 0x00000300;
private const int BS_VCENTER = 0x00000C00;
private const int BS_MULTILINE = 0x00002000;
public static void SetButtonStyle(Button ctrl)
{
IntPtr hWnd;
int style;
// ctrl.Capture = true;
// hWnd = GetCapture();
// ctrl.Capture = false;
// Comment below and uncomment above if using Visual Studio 2003
hWnd = ctrl.Handle;
style = GetWindowLong(hWnd, GWL_STYLE);
SetWindowLong(hWnd, GWL_STYLE, (style | BS_CENTER | BS_VCENTER | BS_MULTILINE));
ctrl.Refresh();
}
It looks about exactly like yours, but I have not tested it personally.
User contributions licensed under CC BY-SA 3.0