2014-10-09 102 views
1

我一直在使用rtf框在Winforms應用程序中運行一段時間,作爲我的外部硬件設備和串口上的PC之間的通信接口運行。我遇到的問題是,在選擇文本時使用任何顏色更改示例(在我的實際命令通過串行之前發送)時,從外部設備回送的回顯也會更改一些文本顏色。WinForm RichTextBox文本顏色變化太多字符

發送符號';'我收到回聲以及來自設備的響應全部用文字着色。

;;[UART+ERROR] 

我收到的事件處理程序是標準的:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
    { 
     //fking threading 
     string rxString = serialPort1.ReadExisting(); // running on worker thread 

     this.Invoke((MethodInvoker)delegate 
     { 
      textLog.AppendText(rxString); // runs on UI thread 
     }); 
    } 

要寫信給我用下面(以及許多其他我也嘗試過)的例子讓我的應用程序正在操作的屏幕。我不確定我做錯了什麼。

private void AppendTextColor(RichTextBox box, Color color, string text) 
    { 
     int start = box.TextLength; 
     box.AppendText(text); 
     int end = box.TextLength; 

     // Textbox may transform chars, so (end-start) != text.Length 
     box.Select(start, end - start); 
     { 
      box.SelectionColor = color; 
      // could set box.SelectionBackColor, box.SelectionFont too. 
     } 
     box.SelectionLength = 0; // clear 
    } 
+0

所以你想按顏色分開命令和響應,命令文本的顏色是黑色(默認),響應是紅色的,但是當你將響應追加到RichTextBox時,命令文本也變成了紅色? – kennyzx 2014-10-09 07:30:53

+0

這就是對的!這樣做會讓他們更容易閱讀! – Larry 2014-10-09 22:31:01

+1

您可以調用AppendTextColor來顯示命令和響應,並指定不同的顏色。如果您只是調用AppendText來顯示響應,則顏色不是默認顏色,而是設置爲命令的顏色。考慮一下MS WORD,如果在選擇之後設計選擇並鍵入,則新內容的風格與選擇相同。 – kennyzx 2014-10-10 01:34:34

回答

2

你的選擇()調用離開SelectionStart酒店在所附的文本,而不是文本的結束的開始。像你這樣的SelectionLength你可以恢復它,但更簡單的方法來做到這一點是:

private static void AppendTextColor(RichTextBox box, Color color, string text) { 
     box.SelectionStart = box.Text.Length; // Optional 
     var oldcolor = box.SelectionColor; 
     box.SelectionColor = color; 
     box.AppendText(text); 
     box.SelectionColor = oldcolor; 
    } 

注意//可選評論,當用戶無法編輯的文本是沒有必要的。

請注意,您的代碼中存在非常嚴重的防火軟管問題。您以非常高的速度調用Invoke(),當盒子開始填充時,可能導致UI線程開始刻錄100%核心。很容易知道這種情況何時發生,您無法再看到更新,並且程序停止響應輸入。在DataReceived事件處理程序中需要緩衝,使用ReadLine()而不是ReadExisting()通常是實現此目的的簡單方法。並且使用BeginInvoke()代替,Invoke()爲非常可能導致SerialPort.Close()調用死鎖的

1

您需要的顏色恢復到RTB的普通文本的顏色:

box.SelectionStart = box.Text.Length; // clear.. 
box.SelectionLength = 0; // clear  // ..selection 
box.SelectionColor = box.ForeColor; // reset color