TextBox.TextAlign右侧对齐在某些条件下没有效果?

gus*_*gus 2 c# visual-studio-2010 winforms

我在Visual C#Express 2010表单应用程序中有一个路径选择器.

我使用a FolderBrowserDialog和a(单行)TextBox来显示所选路径.在我的UI刷新代码中使用以下行.

this.textBoxFolder.Text = this.folderBrowserDialog1.SelectedPath;
Run Code Online (Sandbox Code Playgroud)

只读属性设置为,并textAlign设置属性设置为正确使用表单设计器,因为所选择的路径往往长于文本框,我更喜欢展示路径的右侧.表单设计器生成:

// 
// textBoxFolder
// 
this.textBoxFolder.Location = new System.Drawing.Point(40, 72);
this.textBoxFolder.Name = "textBoxFolder";
this.textBoxFolder.ReadOnly = true;
this.textBoxFolder.Size = new System.Drawing.Size(160, 20);
this.textBoxFolder.TabIndex = 13;
this.textBoxFolder.TabStop = false;
this.textBoxFolder.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
Run Code Online (Sandbox Code Playgroud)

每当所选路径短于文本框大小时,右对齐就会起作用.(但这不是很重要)

每当所选路径长于文本框大小时,右对齐无效,文本框中的字符串将显示为最左边的字符可见,最右边的字符是隐藏的.

我知道,在一个正常的单行文本框(ReadOnly = false),当一个过长的字符串是手工键入,最右边的字符是可见的,甚至当焦点消失,不管的textAlign设置是否被设置为左/右/中心!

换句话说,我的目标是,当TextBox.Text以编程方式设置(而不是键入),并且字符串长于TextBox的宽度时,如何才能使最右边的字符可见?

Moh*_*han 5

TextAlign您应该将插入符号移动到最后一个字符,而不是设置属性:

textBoxFolder.Text = this.folderBrowserDialog1.SelectedPath;
textBoxFolder.SelectionStart = textBox1.Text.Length - 1;
Run Code Online (Sandbox Code Playgroud)

设置SelectionStart实际上将插入符号移动到指定位置.这使得该位置的角色可见TextBox.

如果您可以使用Label而不是文本框,则可以使用Hans Passant创建的文本框,TextFormatFlags.PathEllipses在绘制文本时使用标记.