在richtextbox中保留一定数量的行?

时间:2017-08-28 16:39:03

标签: c# winforms

我想在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连续运行时,我应该怎么做才能顺利进行?

2 个答案:

答案 0 :(得分:1)

一种选择是取消挂接侦听器,执行更新,然后在退出函数时重新挂接侦听器。

private void txt_Log_TextChanged(object sender, EventArgs e)
{
    txt_Log.TextChanged -= this.txt_Log_TextChanged;

    //make you're updates here...

    txt_Log.TextChanged += this.txt_Log_TextChanged;
}

答案 1 :(得分: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();
}