Winforms - 为要在文本框中显示的部分文本添加下划线

本文关键字:文本 下划线 添加 显示 Winforms | 更新日期: 2023-09-27 18:36:09

我有一行文本要显示,我想做的是只在显示中文本的标题部分添加下划线。请问我该如何完成此操作?

消息:这是客户端名称的消息。

其中"消息:"带有下划线。

Winforms - 为要在文本框中显示的部分文本添加下划线

改用 RichTextBox !

    this.myRichTextBox.SelectionStart = 0;
    this.myRichTextBox.SelectionLength = this.contactsTextBox.Text.Length-1;
    myRichTextBox.SelectionFont = new Font(myRichTextBox.SelectionFont, FontStyle.Underline);
    this.myRichTextBox.SelectionLength = 0;

您可以使用 RichTextBox 控件执行该下划线

  int start = rtbTextBox.Text.IndexOf("Message:", StringComparison.CurrentCultureIgnoreCase);
  if(start > 0)
  {
       rtbTextBox.SelectionStart = start;         
       rtbTextBox.SelectionLength = "Message:".Length-1;         
       rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
       rtbTextBox.SelectionLength = 0; 
  }

此示例直接使用您在问题中提供的文本。如果将此代码封装在私有方法中并传入标题文本会更好。

例如:

private void UnderlineHeading(string heading)
{
    int start = rtbTextBox.Text.IndexOf(heading, StringComparison.CurrentCultureIgnoreCase);
    if(start > 0)
    {
         rtbTextBox.SelectionStart = start;         
         rtbTextBox.SelectionLength = heading.Length-1;         
         rtbTextBox.SelectionFont = new Font(rtbTextBox.SelectionFont, FontStyle.Underline);
         rtbTextBox.SelectionLength = 0; 
    }
}

并从您的表格中呼叫:UnderlineHeading("Message:");

如果要

使用格式文本框显示文本,可以执行以下操作:

richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = "Message:";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = " This is a message for Name of Client.";

或者,如果消息是动态的,并且标头和文本始终用冒号分隔,则可以执行以下操作:

string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Underline);
richTextBox1.SelectedText = parts[0] + ":";
richTextBox1.SelectionFont = new Font("Times New Roman", 10, FontStyle.Regular);
richTextBox1.SelectedText = parts[1];

或者,如果要在标签中动态显示文本,可以执行以下操作:

string message = "Message: This is a message for Name of Client";
string[] parts = message.Split(':');
Label heading = new Label();
heading.Text = parts[0] + ":";
heading.Font= new Font("Times New Roman", 10, FontStyle.Underline);
heading.AutoSize = true;
flowLayoutPanel1.Controls.Add(heading);
Label message = new Label();
message.Text = parts[1];
message.Font = new Font("Times New Roman", 10, FontStyle.Regular);
message.AutoSize = true;
flowLayoutPanel1.Controls.Add(message);

只是一个想法,您可以使用屏蔽文本框或创建具有下划线的富文本框的自定义控件,并在客户端应用程序中使用它。我听说有机会使用 GDI+ api 创建带有下划线的文本框,但不确定。

谢谢马赫什·科特卡尔