现在的位置: 首页 > 综合 > 正文

RichTextBox添加文本注意

2012年06月03日 ⁄ 综合 ⁄ 共 2038字 ⁄ 字号 评论关闭

     公司的系統有一個新的要求,很簡單,就是在顯示文章的時候署名、日期、正文的顏色和字體要各不相同。這是個簡單的不要再簡單的要求了。但是在實現的時候卻花了我一個小時,是不是有點不可思議?呵呵,就是一個小地方的偏差。

     這個功能需要用到RichTextBox這個控件,于是我寫了一個添加文本的方法來簡單實現:

private void AddRichTextBoxText(string strText, Color TextColor, float FontSize)
        
{
            
int iTextLength = rBox.TextLength;

            rBox.Text += strText;
            rBox.SelectionStart 
= iTextLength;
            rBox.SelectionLength 
= strText.Length;
            rBox.SelectionFont 
= new Font("宋体", FontSize);
            rBox.SelectionColor 
= TextColor;            
        }

     寫完,測試。輸入第一段文字,沒問題,輸入第二段文字,也沒問題,輸入第三段文字,我發現第二段文字的字體和顏色竟然和第一段文字一樣了。看了看代碼,沒有發現有什么不對的地方。無數次的測試后發現,每當有后一段的文字輸入,前面所有段落的文字都會變成和第一段一樣的字體和顏色。搞到后來甚至開始懷疑是不是這個控件有BUG了。

     而后在遍歷成員的時候發現了AppendText這個方法,這個和直接對文本進行操作有什么區別?不知道。抱著試試看的心情,把代碼改了一下:

private void AddRichTextBoxText(string strText, Color TextColor, float FontSize)
        
{
            
int iTextLength = rtxtReply.TextLength;

            rtxtReply.AppendText(strText);
            rtxtReply.SelectionStart 
= iTextLength;
            rtxtReply.SelectionLength 
= strText.Length;
            rtxtReply.SelectionFont 
= new Font("宋体", FontSize);
            rtxtReply.SelectionColor 
= TextColor;            
        }

     測試后竟然發現,成功了。原先的問題都不復存在了。在高興之余也實在搞不懂這兩種做法之間到底有何差別,可能是控件內部機制上的問題吧。

     順便寫一個在改變文本顏色的時候,調用API防止控件閃爍的現象的方法。

//使用win32api:SendMessage来防止控件着色时的闪烁现象        
[System.Runtime.InteropServices.DllImport("user32")]
        
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
        
private const int WM_SETREDRAW = 0xB;

        
private void AddRichTextBoxText(string strText, Color TextColor, float FontSize)
        
{
            
int iTextLength = rtxtReply.TextLength;

            rtxtReply.AppendText(strText);

            SendMessage(
base.Handle, WM_SETREDRAW, 0, IntPtr.Zero);

            rtxtReply.SelectionStart 
= iTextLength;
            rtxtReply.SelectionLength 
= strText.Length;
            rtxtReply.SelectionFont 
= new Font("宋体", FontSize);
            rtxtReply.SelectionColor 
= TextColor;            
        }

抱歉!评论已关闭.