我一直在創建一個自定義的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。 –