如何在C#中的文本框的末尾写入文本?
问题描述:
我正在用C#编写一个聊天应用程序,并且我还希望在消息后面显示消息到达的时间,从右侧开始?
如何从右侧开始写入文本框或richTextBox?如何在C#中的文本框的末尾写入文本?
这是我的代码看起来现在:
textBox1.SelectionFont = new Font("Arial", 12, FontStyle.Regular);
textBox1.AppendText(text + "\n");
textBox1.SelectionFont = new Font("Arial", 8, FontStyle.Italic);
textBox1.AppendText("sent at " + DateTime.Now.ToString("h:mm") + "\n");
答
使用TextBox.TextAlignment Property
textbox1.TextAlignment = TextAlignment.Right;
否则,如果它是一个固定的大小,并且没有换行,你可以这样做这
string time = "12:34PM";
string text = "Hello".PadRight(100) + time;
textBox1.AppendText(text + "\n");
或使用您现有的代码...也许是这样的?
textBox1.SelectionFont = new Font("Arial", 12, FontStyle.Regular);
textBox1.AppendText(text + "\n");
textBox1.SelectionFont = new Font("Arial", 8, FontStyle.Italic);
textBox1.AppendText(("sent at " + DateTime.Now.ToString("h:mm")).PadLeft(100) + "\n");
+0
谢谢:)它与Alignment属性一起工作: –
答
谢谢:) 它有取向性的工作:
textBox1.SelectionFont = new Font("Arial", 12, FontStyle.Regular);
textBox1.AppendText(text + "\n");
textBox1.SelectionFont = new Font("Arial", 8, FontStyle.Italic);
textBox1.SelectionAlignment = HorizontalAlignment.Right;
textBox1.AppendText("sent at " + DateTime.Now.ToString("h:mm") + "\n");
textBox1.SelectionAlignment = HorizontalAlignment.Left;
}
答
相反AppendText通过的,我会建议的String.Format
string text = "This is the message \n";
string dt = "sent at " + DateTime.Now.ToString("h:mm") + "\n"
textBox1.Text = string.Format("{0} {1}", text, dt);
你也可以将字符串使用后主文本的长度函数,并添加日期后。
你问的是如何正确对齐一半的文字? – Andrew
这是使用Windows Forms还是WPF? –