我正在尝试使用Owner-drawing a 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);
}
}