:线程里画图的问题(50分)

  • 主题发起人 主题发起人 wyly
  • 开始时间 开始时间
W

wyly

Unregistered / Unconfirmed
GUEST, unregistred user!
我要在线程里往主窗口画图,所以传了个窗口的HDC进去。
如果传的是Form1->Handle,然后用GetDC来得到HDC,十分成功。
如果直接传Form1->Canvas->Handle,就没什么反应,并且发现这个Form1->Canvas->Handle会变,每次传的不一样。为什么呢?
如果我要在PaintBox上绘图,也发现传的CanVas->Handle会变,在线程中用他作为HDC绘图没反应。
 
Delphi5开发人员指南第11章里有:)
 
问题是我没这本书,请点拨一下即可
 
4个菜单项、颜色对话框
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus;
type
TMainForm = class(TForm)
MainMenu1: TMainMenu;
sadf1: TMenuItem;
N11: TMenuItem;
N21: TMenuItem;
N31: TMenuItem;
N41: TMenuItem;
ColorDialog1: TColorDialog;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure N11Click(Sender: TObject);
procedure N21Click(Sender: TObject);
procedure N31Click(Sender: TObject);
procedure N41Click(Sender: TObject);
private
{ Private declarations }
ThreadList :TList;
public
{ Public declarations }
end;

TDrawThread=Class(TThread)
private
FColor :TColor;
FForm :TForm;
public
Constructor Create(AForm :TForm;
AColor :TColor);
procedure Execute;override;
end;

var
MainForm: TMainForm;
implementation
{$R *.DFM}
Constructor TDrawThread.Create(AForm :TForm;
AColor :TColor);
begin
FColor :=AColor;
FForm :=AForm;
Inherited Create(False);
end;

procedure TDrawThread.Execute;
var
p1,p2 :TPoint;
procedure GetRandomColor;
var
MaxX,MaxY :Integer;
begin
MaxX :=FForm.ClientWidth;
MaxY :=FForm.ClientHeight;
p1.x :=Random(MaxX);
p1.y :=Random(MaxY);
p2.x :=Random(MaxX);
p2.y :=Random(MaxY);
end;

begin
FreeOnTerminate :=True;
While not (Terminated or Application.Terminated)do
begin
GetRandomColor;
with FForm.Canvasdo
begin
Lock;
Pen.Color :=FColor;
MoveTo(p1.x,p1.y);
LineTo(p2.x,p2.y);
unLock;
end;
end;
end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
ThreadList :=TList.Create;
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
N41Click(nil);
ThreadList.Free;
end;

procedure TMainForm.N11Click(Sender: TObject);
begin
if ColorDialog1.Execute then
ThreadList.Add(TDrawThread.Create(Self,ColorDialog1.Color));
end;

procedure TMainForm.N21Click(Sender: TObject);
begin
TDrawThread(ThreadList[ThreadList.Count-1]).Terminate;
ThreadList.Delete(ThreadList.Count-1);
end;

procedure TMainForm.N31Click(Sender: TObject);
var
I :Integer;
begin
for I :=1 to 30do
ThreadList.Add(TDrawThread.Create(Self,Random(MaxInt)));
end;

procedure TMainForm.N41Click(Sender: TObject);
var
I :Integer;
begin
Cursor :=crHourGlass;
try
for I :=ThreadList.Count-1do
wnto 0do
begin
TDrawThread(ThreadList).Terminate;
TDrawThread(ThreadList).WaitFor;
end;
ThreadList.Clear;
finally
Cursor :=crDefault;
end;
end;

initialization
Randomize;
end.
 
谢谢tyn,但我觉得您的方法是delphi的方法。我想用标准的windows的方法。呵呵
 
你还管他是黑猫白猫!
 
呵呵,搞定
 
后退
顶部