Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms: right aligned label autosize

Right now I clarify this may be a duplicated question from: Right-aligned labels in WinForms But non of the answers satisfied me.

The problem is very simple:

I have a right aligned label with autosize set to true. The expected behavior is that when the text is increased the right coordinate remain unchanged. But that is not what it happens. The left coordinate is the one which remains unchanged.

My app is kind of small, so I don't want to start putting controls into panels and so. So I've tried all solutions that involved ONLY label properties. The only one which worked is to set autosize to false and over-size it. (Accepted solution of question Nº1692383). But it is really ugly! I'd really like to avoid that.

Any other possible solution?

like image 300
Diego Avatar asked Oct 21 '10 14:10

Diego


1 Answers

One solution would be to capture the label's right margin in the form constructor, and in the label SizeChanged event, reset the location based on the initial right margin, the label's current Width and the label Parent's current Width.

This also assumes the label is anchored on the right to handle form resizing.

private readonly int _rightMargin;

public Form1()
{
    InitializeComponent();

    _rightMargin = label1.Parent.Width - label1.Right;
}

private void label1_SizeChanged(object sender, EventArgs e)
{
    label1.Location = new Point(label1.Parent.Width - _rightMargin - label1.Width, label1.Top);
}
like image 134
Jeff Ogata Avatar answered Nov 16 '22 03:11

Jeff Ogata