2012-06-04 32 views
2

我有一行文本要顯示,而我想要執行的操作只是在顯示中僅對文本的標題部分加下劃線。我該如何做到這一點?Winforms - 要在文本框中顯示的文本的下劃線部分

消息:這是客戶名稱的消息。

其中「消息:」加下劃線。

+1

您正在使用這種錯誤的控制。如果你真的感到壓倒性的理由做下劃線,然後選擇RichTextBox。 – Steve

+0

我從來沒有使用過其中之一。我如何格式化文本以強調我需要它的那部分字符串? – Kobojunkie

+1

你想要顯示的文字是什麼?你怎麼知道文本的哪一部分是標題? –

回答

2

如果你想使用豐富的文本框來顯示文本,你可以做這樣的事情:

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

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

+0

哇,我發誓我寫它,我們完成幾乎相同:) –

+0

我更新了我的原始帖子與字符串的示例。我想要的是隻指定特定行上的開始文本加下劃線。 – Kobojunkie

+0

我已經使用您在問題中提供的文字和位置更新了我的答案。 – Steve

5

使用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; 
0

想一想,您可以使用蒙面文本框或使用richtextbox創建自定義控件,並在客戶端應用程序中使用下劃線和下劃線。我聽說有創建帶有GDI + api下劃線的文本框的機會,但不確定。

感謝 馬赫什kotekar