【问题标题】:how to write text starting from the end of the textBox in C# ?如何在 C# 中从 textBox 的末尾开始编写文本?
【发布时间】:2017-02-11 06:30:27
【问题描述】:

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

【问题讨论】:

  • 你问的是如何右对齐一半的文字?
  • 这是使用 Windows 窗体还是 WPF?

标签: c# textbox richtextbox reverse


【解决方案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");

【讨论】:

    【解决方案2】:

    谢谢 :) 它与对齐属性一起使用:

            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;
    
        }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多