簡體   English   中英

使用C#在RichTextBox中的單詞下划線

[英]draw underline to words in RichTextBox using c#

我正在嘗試使用所有者繪制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);
        }
    }

您是否在按下空格鍵時嘗試過一些設置標記的方法? 然后釋放它時,取消設置該標志。 像這樣:

    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方法中,如果設置了標志,則僅執行自定義波浪線代碼。 我假設您此時已將文本框設置為只讀,否則您將得到一個充滿空格的文本框...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM