如何在 C# 中从文本框的末尾开始编写文本?

how to write text starting from the end of the textBox in C# ?

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

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

谢谢:) 它与对齐方式一起工作 属性 :

        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;

    }

我建议 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);

您也可以在使用正文的长度函数后附加字符串,并在其后添加日期。