请教:Canvas.TextOut的问题?(30分)

  • 主题发起人 主题发起人 formater
  • 开始时间 开始时间
F

formater

Unregistered / Unconfirmed
GUEST, unregistred user!
要求:动态生成一个GroupBox,在GroupBox里头用TextOut输出文字,我的Code如下:
procedure TForm1.Button1Click(Sender: TObject);
var
dc:hdc;
groupbox1:tgroupbox;
a:tcanvas;
begin
a:=tcanvas.Create;
groupbox1:=tgroupbox.Create(self);
groupbox1.Parent:=self;
groupbox1.SetBounds(10,10,100,100);
groupbox1.Show;
dc:=getdc(groupbox1.Handle);
a.Handle:=dc;
a.Brush.Style:=bsClear;
a.TextOut(30,40,'3333');
a.Free;
end;
结果:只能显示GroupBox,一个字都没显示,但是也没提示错误。
说明:如果GroupBox不是动态生成,而是直接从控件板里拉下来,则可以正确显示。
 
TmyGroupBox=class(TGroupBox)
protected
procedure Paint;override;
procedure WriteText(txt:string);
end;


implementation

{$R *.dfm}
procedure TmyGroupBox.Paint;
var
dc:hdc;
begin
inherited;
dc:=GetDc(Handle);
TextOut(dc,30,40,'asasdfasdfadf',255);
end;
重载它的PAINT吧
 
Canvas.font.color := clBlack;
 
因为你的GroupBox是一个局部变量,
而当GroupBox1.Show后并不是立即产生GroupBox1.Paint过程
而是先执行你的a.textOut了,所以必须改写:
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
groupbox1:tgroupbox;
public
end;

var
Form1: TForm1;

implementation
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
groupbox1:=tgroupbox.Create(self);
groupbox1.Parent:=self;
groupbox1.SetBounds(10,10,100,100);
groupbox1.Show;
button2Click(nil);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
dc:hdc;
a:tcanvas;
begin
a:=tcanvas.Create;
dc:=getdc(groupbox1.Handle);
a.Handle:=dc;
a.Brush.Style:=bsClear;
a.TextOut(30,40,'3333');
a.Free;
end;

end.
 
这样也可以,但没法直接访问GroupBox1了
procedure TForm1.Button1Click(Sender: TObject);
var
dc:hdc;
groupbox1:tgroupbox;
a:tcanvas;
begin
a:=tcanvas.Create;
groupbox1:=tgroupbox.Create(self);
groupbox1.Parent:=self;
groupbox1.SetBounds(10,10,100,100);
groupbox1.Show;
Application.ProcessMessages;//先让GroupBox1.Show完成
dc:=getdc(groupbox1.Handle);
a.Handle:=dc;
a.Brush.Style:=bsClear;
a.TextOut(30,40,'3333');
a.Free;
end;
 
多人接受答案了。
 
后退
顶部