1

According to my understanding, the code below should right-justify the text if the text is longer than the textbox can show, otherwise it keeps it left-justified.

The problem is that it doesn't actually do this and it's acting really odd. Short strings end up right-justified sometimes and long strings are always left-justified.

What am I doing wrong?

private void textBoxCurrentConfig_TextChanged(object sender, EventArgs e)
{
    SizeF stringSize = new SizeF();
    stringSize = TextRenderer.MeasureText(textBoxCurrentConfig.Text, textBoxCurrentConfig.Font);

    float currentTextWidth = stringSize.Width;
    float allowedTextWidth = textBoxCurrentConfig.Size.Width - 10;

    if (currentTextWidth >= allowedTextWidth) // if the text we want to display is larger than the textbox can hold, right justify it to show the filename
    {
        textBoxCurrentConfig.TextAlign = HorizontalAlignment.Right; // right justify                
    }
    else // otherwise we can display the entire path
    {
        textBoxCurrentConfig.TextAlign = HorizontalAlignment.Left; // left justify
    }

    textBoxCurrentConfig.Refresh();
    this.Refresh();
}
4

2 回答 2

3

从您的评论中,您想根据文本长度移动光标位置。您可以TextBox.Select()为此使用方法。有关详细信息,请查看 MSDN

所以如果你想在文本的开头移动光标,你可以使用

textBoxCurrentConfig.Select(0, 0);

如果你想在文本末尾移动光标,你可以使用

textBoxCurrentConfig.Select(textBoxCurrentConfig.Text.Length, 0);

于 2012-04-10T17:53:20.643 回答
0

Try to remove

this.Refresh();

It's may cause the page to refresh and return the text box to the original align

于 2012-04-10T09:03:46.840 回答