2017-02-10 77 views
1

我正在用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"); 
+0

你問的是如何正確對齊一半的文字? – Andrew

+0

這是使用Windows Forms還是WPF? –

回答

1

使用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屬性一起工作: –

0

謝謝:) 它有取向性的工作:

 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; 

    } 
0

相反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); 

你也可以將字符串使用後主文本的長度函數,並添加日期後。

相關問題