我一直在创建一个自定义的RichTextBox
控件来向文本区域添加一些额外的图形。从我一直在阅读的内容来看,这个控件默认不会公开它的Paint事件。通过PInvoke调用BeginPaint返回PAINTSTRUCT中的空更新区域
我遵循MSDN上的建议(Painting on a RichTextBox Control)重新公开Paint事件并创建OnPaint
事件处理程序,该程序由WM_PAINT
消息触发。
在OnPaint
方法中,我试图从Win32 API中调用BeginPaint()
来绘制一些图形,但没有绘制任何图形。当我检查PAINTSTRUCT
结构中的rcPaint
字段时,它始终为空(所有值均为0)。所以我的问题是,为什么更新区域总是空的?我肯定错过了什么。
相关代码:
public partial class RichTextBoxEnhanced : RichTextBox
{
private PAINTSTRUCT ps;
new public void OnPaint(PaintEventArgs e)
{
var hdc = BeginPaint(this.Handle, out ps);
FillRect(hdc, ref ps.rcPaint, CreateSolidBrush(100));
Rectangle(hdc, 1000, 2000, 1000, 2000);
EndPaint(this.Handle, ref ps);
Paint?.Invoke(this, e);
}
[DllImport("user32.dll")]
static extern IntPtr BeginPaint(IntPtr hwnd, out PAINTSTRUCT lpPaint);
[DllImport("user32.dll")]
static extern bool EndPaint(IntPtr hWnd, [In] ref PAINTSTRUCT lpPaint);
[DllImport("gdi32.dll")]
static extern IntPtr CreateSolidBrush(uint crColor);
}
我猜测的时候'的OnPaint()'被调用时,.NET已经被称为'调用BeginPaint()'你来填充'PaintEventArgs',所以返回的DC可能是'NULL'(表示失败)... – andlabs
@andlabs,这确实是问题。显然base.WndPrc在到达我的OnPaint方法之前调用BeginPaint。 –