简体   繁体   English

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

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

I am writing a chat application in C#, and I would like also to display the time of the arrival of the message, just after the message, starting from the right?我正在用 C# 编写一个聊天应用程序,我还想显示消息到达的时间,就在消息之后,从右边开始?
How can I write in a textBox or a richTextBox starting from the right?如何从右侧开始在 textBox 或 richTextBox 中书写?

This is how my code looks for now:这是我的代码现在的查找方式:

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

Use the TextBox.TextAlignment Property使用TextBox.TextAlignment 属性

textbox1.TextAlignment = TextAlignment.Right;

Otherwise, if it is a fixed size and there are no line breaks, you could do something like this否则,如果它是固定大小并且没有换行符,你可以做这样的事情

string time = "12:34PM";
string text = "Hello".PadRight(100) + time;
textBox1.AppendText(text + "\n");

or using your existing code... maybe something like this?或使用您现有的代码......也许是这样的?

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

Thanks :) It worked with the alignment property :谢谢 :) 它与对齐属性一起使用:

        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;

    }

Instead of appendtext, I would suggest string.format我建议使用 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);

You could also append the string after using a length function of the main text, and adding the date after.您还可以在使用正文的长度函数后附加字符串,并在之后添加日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM