2017-08-28 30 views
0

我要保持一定數量的RichTextBox的線,所以我做了以下內容:在richtextbox中保留一定數量的行嗎?

private void txt_Log_TextChanged(object sender, EventArgs e) 
    { 
     int max_lines = 200; 
     if (txt_Log.Lines.Length > max_lines) 
     { 
      string[] newLines = new string[max_lines]; 
      Array.Copy(txt_Log.Lines, 1, newLines, 0, max_lines); 
      txt_Log.Lines = newLines; 
     } 
     txt_Log.SelectionStart = txt_Log.Text.Length; 
     txt_Log.ScrollToCaret(); 
    } 

但運行時我Richtextnbox連續閃爍,所以我應該怎麼做這個光滑?

+1

我相信當你再次更新'txt_Log.Lines'屬性的值,則'txt_Log_TextChanged'事件觸發。你可以調試代碼來驗證它嗎? – Dmitry

回答

0

當您更新txt_Log.Lines屬性的值時,txt_Log_TextChanged事件再次觸發。

你可以使用一個變量bool阻止它:

private bool updatingTheText; 

private void txt_Log_TextChanged(object sender, EventArgs e) 
{ 
    if (updatingTheText) 
     return; 

    const int max_lines = 200; 
    if (txt_Log.Lines.Length > max_lines) 
    { 
     string[] newLines = new string[max_lines]; 
     Array.Copy(txt_Log.Lines, 1, newLines, 0, max_lines); 
     updatingTheText = true; // Disable TextChanged event handler 
     txt_Log.Lines = newLines; 
     updatingTheText = false; // Enable TextChanged event handler 
    } 
    txt_Log.SelectionStart = txt_Log.Text.Length; 
    txt_Log.ScrollToCaret(); 
} 
+0

你是對的,textchange事件一再被調用,我嘗試了你的建議,它被減少了,但仍然閃爍很多。 – jimbo

+0

@jimbo你可以使用這些主題的解決方法:[stackoverflow.com/questions/9418024](https://stackoverflow.com/questions/9418024/richtextbox-beginupdate-endupdate-extension-methods-not-working)和[ social.msdn.microsoft.com](https://social.msdn.microsoft.com/Forums/windows/en-US/a6abf4e1-e502-4988-a239-a082afedf4a7/anti-flicker-in-richtextbox-c?forum = winforms) – Dmitry

+0

@jimbo https://stackoverflow.com/help/someone-answers – Dmitry