如何在WinForms中加速自定义渲染?

时间:2014-04-25 07:45:59

标签: c# .net winforms winapi gdi+

我在WinForms应用程序上工作,需要实现拼写检查。

使用Windows消息重绘表单。

    /// <summary>
    /// Processes Windows messages.
    /// </summary>
    /// <param name="msg">
    /// A Windows Message object.
    /// </param>
    protected override void WndProc(ref Message msg)
    {
        switch (msg.Msg)
        {
            case WM_PAINT:
                Invalidate();
                base.WndProc(ref msg);

                if (IsSpellingAutoEnabled)
                {
                    CustomPaint();
                }

                break;

        ...

            default:
                base.WndProc(ref msg);
                break;
        }
    }

方法CustomPaint()如下所示:

private void CustomPaint()
    {
        Bitmap tempBitmap;
        Graphics bufferGraphics;

        tempBitmap = new Bitmap(Width, Height);
        bufferGraphics = Graphics.FromImage(tempBitmap);
        bufferGraphics.Clip = new Region(ClientRectangle);

        _textBoxGraphics = CreateGraphics();
        bufferGraphics.Clear(Color.Transparent);

        foreach (var wordStartIndex in UnderlinedSections.Keys)
        {
            UnderlineWords(wordStartIndex, bufferGraphics);
        }

        _textBoxGraphics.DrawImageUnscaled(tempBitmap, 0, 0);
    }

在UnderlineWords()中,使用以下代码绘制线条:

private void DrawWave(Graphics bufferGraphics, Point startOfLine, Point endOfLine)
    {
        startOfLine.Y--;
        endOfLine.Y--;

        // kvv: Определяем цвет линий подчеркивания.
        var pen = Pens.Red;

        if ((endOfLine.X - startOfLine.X) >= 4)
        {
            var points = new ArrayList();
            for (int i = startOfLine.X; i <= (endOfLine.X - 2); i += 4)
            {
                points.Add(new Point(i, startOfLine.Y));
                points.Add(new Point(i + 2, startOfLine.Y + 2));
            }

            var p = (Point[])points.ToArray(typeof(Point));
            bufferGraphics.DrawLines(pen, p);
        }
    }

使用超过500个字符的文本时,应用程序会挂起。我该如何解决这个问题?

0 个答案:

没有答案