Advertisement
Guest User

Async event component

a guest
Apr 22nd, 2014
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.84 KB | None | 0 0
  1. unit UAsyncEvent;
  2.  
  3. interface
  4.  
  5. uses
  6.   WinAPI.Windows, Winapi.Messages, System.Classes, Vcl.Controls, Vcl.Forms, System.SysUtils, Generics.Collections;
  7.  
  8. const
  9.   WM_ASYNCEVENT = WM_USER + 1001;
  10.  
  11. type
  12.   TAsyncEvent = class(TComponent)
  13.   private
  14.     FHWnd: THandle;
  15.     FProcList: TList<TProc>;
  16.  
  17.     procedure AllocWnd;
  18.     procedure DestroyWnd;
  19.  
  20.     procedure WndProc(var Msg: TMessage); virtual;
  21.     procedure WndProcWrapper(var Message: TMessage);
  22.   protected
  23.     procedure DoAsyncEvent;
  24.   public
  25.     constructor Create(AOwner: TComponent); override;
  26.     destructor Destroy; override;
  27.  
  28.     procedure Post(const proc: TProc);
  29.   end;
  30.  
  31.  
  32.  
  33. procedure Register;
  34.  
  35. implementation
  36.  
  37. procedure Register;
  38. begin
  39.   RegisterComponents('MyComponents', [TAsyncEvent]);
  40. end;
  41.  
  42. { TAsyncEvent }
  43.  
  44. procedure TAsyncEvent.AllocWnd;
  45. begin
  46.   FHWnd := AllocateHWnd(WndProcWrapper);
  47. end;
  48.  
  49. constructor TAsyncEvent.Create(AOwner: TComponent);
  50. begin
  51.   inherited Create(AOwner);
  52.  
  53.   FProcList := TList<TProc>.Create;
  54.   AllocWnd;
  55. end;
  56.  
  57. destructor TAsyncEvent.Destroy;
  58. begin
  59.   DestroyWnd;
  60.  
  61.   FProcList.Free;
  62.  
  63.   inherited;
  64. end;
  65.  
  66. procedure TAsyncEvent.DestroyWnd;
  67. begin
  68.   DestroyWindow(FHWnd);
  69. end;
  70.  
  71. procedure TAsyncEvent.DoAsyncEvent;
  72. var
  73.   proc: TProc;
  74. begin
  75.   Assert(FProcList.Count > 0, 'Consistency error in AsyncEvent');
  76.  
  77.   proc := FProcList[0];
  78.   FProcList.Delete(0);
  79.  
  80.   proc();
  81. end;
  82.  
  83. procedure TAsyncEvent.Post(const proc: TProc);
  84. begin
  85.   FProcList.Add(proc);
  86.   PostMessage(FHWnd, WM_ASYNCEVENT, 0, 0);
  87. end;
  88.  
  89. procedure TAsyncEvent.WndProc(var Msg: TMessage);
  90. begin
  91.   case Msg.Msg of
  92.     WM_ASYNCEVENT: begin
  93.       DoAsyncEvent();
  94.     end;
  95.   end;
  96. end;
  97.  
  98. procedure TAsyncEvent.WndProcWrapper(var Message: TMessage);
  99. begin
  100.   try
  101.     WndProc(Message);
  102.   except
  103.     Application.HandleException(Self);
  104.   end;
  105. end;
  106.  
  107. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement