如何从C#中的textBox结尾开始编写文本?

时间:2017-02-10 21:57:39

标签: c# textbox richtextbox reverse

我正在用C#编写一个聊天应用程序,我还想显示消息到达的时间,就在消息之后,从右边开始?
如何从右边开始写入textBox或richTextBox?

这是我的代码现在的样子:

        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");

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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;

    }

答案 2 :(得分:0)

我建议使用string.format

而不是appendtext
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);

您还可以在使用主文本的长度函数后添加字符串,然后添加日期。