subthread(handling busy operation) notify mainthread to update UI

来源:互联网 发布:返利网源码下载 编辑:程序博客网 时间:2024/06/05 17:36

Call PostMessage inside TMyThread.Execute to tell Main Form to update UI

unit MyConsts;

interface

uses Messages;

const
 WM_UPDATE_STATUS = WM_USER + 1;

implementation

end.

///////////////////////////////////////////////////////////////////////

unit Unit1;

interface

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


type
  TForm1 = class(TForm)
    btnSpawn: TButton;
    pgsBar: TProgressBar;
    lblPC: TLabel;
    procedure btnSpawnClick(Sender: TObject);
  private
    { Private declarations }
  protected
   procedure OnUpdateStatus(var Msg: TMessage); message WM_UPDATE_STATUS;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.btnSpawnClick(Sender: TObject);
var
 AThread: TMyThread;
begin
 AThread := TMyThread.CreateNew(100000, Handle);
  AThread.Resume;
end;

procedure TForm1.OnUpdateStatus(var Msg: TMessage);
begin
 pgsBar.Position := Msg.WParam;
  lblPC.Caption := Format('%d%s', [Msg.WParam, '%']);
end;

end.

///////////////////////////////////////////////////////////////////////

unit Unit2;

interface

uses
  Classes, Windows, Messages;


type
  TMyThread = class(TThread)
  private
    { Private declarations }
    FHandle: THandle;
    FCounter: Integer;
  protected
    procedure Execute; override;

  public
    constructor CreateNew(Counter: Integer; AHandle: THandle);
  end;

implementation

uses MyConsts;

constructor TMyThread.CreateNew(Counter: Integer; AHandle: THandle);
begin
 inherited Create(true);
 FCounter := Counter;
  FHandle := AHandle;

  FreeOnTerminate := true;
end;

procedure TMyThread.Execute;
var
 i, r: Integer;
begin
  for i := 1 to 100 do
  begin
    PostMessage(FHandle, WM_UPDATE_STATUS, i, 0);
      Sleep(100);
  end;
end;

end.