如何使用富文本框突出显示语法并禁用自动滚动

本文关键字:滚动 语法 显示 何使用 文本 | 更新日期: 2023-09-27 18:34:51

所以我花了大约三天的时间搜索互联网 - Google,Stack Overflow,Microsoft的C#文档 - 没有产生任何有用的结果。 我的问题是我最近创建了一个非常灵活和快速的语法,突出显示了 RichTextBox,它保存在 UserControl 中。 我使用WinForms创建了这个。

然而,尽管我的项目速度和灵活性很高,但仍然存在一个明显且极其令人讨厌的故障。 这个故障是我的富文本框会自动滚动...都。。。这。。。时间。 我不希望这种自动滚动发生。 当我突出显示文本时,我希望用户看不到移动或过渡,而只看到彩色字母和符号。 以下是影响项目语法突出显示的代码:

    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

    private void DoHighlight()
    {
        if (TextEditor.Text.Length <= 0)
            return;
        int visibleStart = TextEditor.GetCharIndexFromPosition(new Point(1, 1));
        int visibleEnd = TextEditor.GetCharIndexFromPosition(new Point(1, TextEditor.Height - 1)) + TextEditor.Lines[BottomLine].Length;
        int[] curSelection = new [] {TextEditor.SelectionStart,TextEditor.SelectionLength};
        LineCounter.Focus();
        SendMessage(TextEditor.Handle, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);
        TextEditor.SelectAll();
        TextEditor.SelectionColor = TextEditor.ForeColor;
        if (parser != null)
            parser.HighlightText(this, visibleStart, visibleEnd);
        TextEditor.SelectionStart = curSelection[0];
        TextEditor.SelectionLength = curSelection[1];
        SendMessage(TextEditor.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);
        TextEditor.Invalidate();
        TextEditor.Focus();
    }

进行一些调试并使用许多断点后,我确定在 DoHighlight(( 方法完成并运行其过程之前不会发生自动滚动。

另外,我认为重要的是要注意,每当RichTextBox的文本现在更改时,都会调用此DoHighlight((方法。

如何使用富文本框突出显示语法并禁用自动滚动

将DoHighlight((方法放在后台进程中。喜欢这个:

  BackgroundWorker bgw = new BackgroundWorker();
  bgw.DoWork += DoHighlight();
  bgw.RunWorkerAsync();

有了这个技巧,你的DoHighlight((方法将并行运行,并且可以发生自动滚动。

您也可以在DoHighlight((方法中使用此代码:

Application.DoEvents();

这将暂停您的方法并执行其他事件,然后返回到您的方法。