使用c为RichTextBox中的单词画下划线

本文关键字:单词画 下划线 RichTextBox 使用 | 更新日期: 2023-09-27 18:28:42

我正在尝试使用所有者绘制Windows.Forms TextBox的代码为RichTextBox中的单词画下划线。此代码的问题在于它在每个绘制事件上都画下划线。我只想在按下空格键检查拼写时绘制,如果发现错误,请在下面加下划线。如何修改代码以适应这种情况?

 #region Custom Paint variables
    private Bitmap bitmap;
    private Graphics textBoxGraphics;
    private Graphics bufferGraphics;
    #endregion
 public CustomRichTextBox()
    {
        this.bitmap = new Bitmap(Width, Height);
        this.bufferGraphics = Graphics.FromImage(this.bitmap);
        this.bufferGraphics.Clip = new Region(ClientRectangle);
        this.textBoxGraphics = Graphics.FromHwnd(Handle);
        // Start receiving messages (make sure you call ReleaseHandle on Dispose):  
      //  this.AssignHandle(Handle);
    }
    public void DrawUnderline(Point start,Point end)
    {
        Invalidate();
        CustomPaint(start,end);
        SendMessage(new HandleRef(this, this.Handle), 15, 0, 0);
    }
    private void CustomPaint(Point start,Point end)
    {
            // clear the graphics buffer  
            bufferGraphics.Clear(Color.Transparent);
           start.Y += 14;
            end.Y += 14;
            end.X += 1;
            // Draw the wavy underline.  
            DrawWave(start, end);
            // Now we just draw our internal buffer on top of the TextBox.  
            // Everything should be at the right place.  
            textBoxGraphics.DrawImageUnscaled(bitmap, 0, 0);

    }
    private void DrawWave(Point start, Point end)
    {
        Pen pen = Pens.Red;
        if ((end.X - start.X) > 4)
        {
            var pl = new ArrayList();
            for (int i = start.X; i <= (end.X - 2); i += 4)
            {
                pl.Add(new Point(i, start.Y));
                pl.Add(new Point(i + 2, start.Y + 2));
            }
            Point[] p = (Point[])pl.ToArray(typeof(Point));
            bufferGraphics.DrawLines(pen, p);
        }
        else
        {
            bufferGraphics.DrawLine(pen, start, end);
        }
    }

使用c为RichTextBox中的单词画下划线

您是否尝试过在按下空格键时设置标志的方法?然后,当它被释放时,取消设置标志。类似这样的东西:

    private volatile bool m_SpaceDepressed;
    private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Space)
        {
            // Set Flag
            m_SpaceDepressed = true;
        }
    }
    private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Space)
        {
            // UnSet Flag
            m_SpaceDepressed = false;
        }
    }

然后,在OnPaint方法中,仅在设置了标志的情况下执行自定义波浪线代码。我假设你已经将你的文本框设置为只读,否则你会得到一个充满空格的文本框。。。