我的项目中有一个框架(TFrame
的后代),想在上面画一些东西。
正如我从论坛中看到的那样,常见的方法是覆盖PaintWindow
方法。
我在一个干净的项目上试过这个:
type
TMyFrame = class(TFrame)
private
FCanvas: TCanvas;
protected
procedure PaintWindow(DC: HDC); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
end;
implementation
{$R *.dfm}
constructor TMyFrame.Create(AOwner: TComponent);
begin
inherited;
FCanvas := TCanvas.Create();
end;
destructor TMyFrame.Destroy();
begin
FCanvas.Free();
inherited;
end;
procedure TMyFrame.PaintWindow(DC: HDC);
begin
inherited;
FCanvas.Handle := DC;
FCanvas.Pen.Width := 3;
FCanvas.Pen.Color := clRed;
FCanvas.MoveTo(0, 0);
FCanvas.LineTo(ClientWidth, ClientHeight);
FCanvas.Pen.Color := clGreen;
FCanvas.MoveTo(ClientWidth, 0);
FCanvas.LineTo(0, ClientHeight);
end;
但是,在将我的框架放在主窗体上之后,调试器从未进入此方法,直到我DoubleBuffered
在框架的属性中启用。的任何值ParentBackground
都不影响结果。
覆盖WM_PAINT
处理程序也解决了问题:
type
TMyFrame = class(TFrame)
protected
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
...
procedure TMyFrame.WMPaint(var Message: TWMPaint);
begin
inherited;
FCanvas.Handle := GetDC(Handle);
FCanvas.Pen.Width := 3;
FCanvas.Pen.Color := clRed;
FCanvas.MoveTo(0, 0);
FCanvas.LineTo(ClientWidth, ClientHeight);
FCanvas.Pen.Color := clGreen;
FCanvas.MoveTo(ClientWidth, 0);
FCanvas.LineTo(0, ClientHeight);
ReleaseDC(Handle, FCanvas.Handle);
end;
无论将哪些值分配给DoubleBuffered
或,此代码始终绘制交叉线ParentBackground
。
但是当我尝试使用BeginPaint
/EndPaint
而不是GetDC
/ReleaseDC
时,问题又回来了:
procedure TMyFrame.WMPaint(var Message: TWMPaint);
var
PS: PAINTSTRUCT;
begin
inherited;
FCanvas.Handle := BeginPaint(Handle, PS);
FCanvas.Pen.Width := 3;
FCanvas.Pen.Color := clRed;
FCanvas.MoveTo(0, 0);
FCanvas.LineTo(ClientWidth, ClientHeight);
FCanvas.Pen.Color := clGreen;
FCanvas.MoveTo(ClientWidth, 0);
FCanvas.LineTo(0, ClientHeight);
EndPaint(Handle, PS);
end;
FCanvas.Handle 非零,但结果是一个空白帧。在这种情况下,设置DoubleBuffered
或ParentBackground
不更改任何内容。
也许我叫他们错了?
现在我使用带有/的WM_PAINT
处理程序,因为我不想在这个框架上启用。另外我担心其他程序员在将我的框架放入他们的项目后会不小心禁用,并且会和我一样头疼。GetDC
ReleaseDC
DoubleBuffered
DoubleBuffered
但也许有更安全和正确的方法在框架表面上绘画?