我正在尝试使用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);
}
}
答案 0 :(得分:0)
当按下空格键时,您是否尝试过设置标志的内容?然后当它被释放时,取消设置标志。像这样:
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方法中,如果设置了标志,则只执行自定义波浪线代码。我假设您已将文本框设置为仅在此时读取,否则您将获得一个充满空格的文本框...