|
|
|
Previous article is a theoretical introduction into windows
and message handling. Now let's look at the example. Terms.May be you remember that previous example shows how to create message (task) queue processed in context of the separate thread and communications between the main and working threads. Like in previous example. let's assume that the thread receives abstract blocks of data (TILClientData objects) and "process" them sequentially calling its "ProcessData()" method. Previous implementation of TMyThread create critical section protected list and manage the queue on it's own. Now Windows will manage queue for us (or we'll use standard thread message queue). You will see that the source code is somewhat smaller. AllocateHWnd and DeallocateHWnd functions.The window should be created in order to receive messages and process them in the context of the thread. The easiest way to create window is AllocateHWnd function (Forms unit). It create popup window of 'TPUtilWindow' class. The only needed parameter is address of the window function, so you do not need to specify numerous parameters of CreateWindows API function. Please note that window function should be a class method and is called with object instance in the Self parameter. Handle returned by AllocateHWnd should be further closed by DeallocateHWnd. Source code.TMYTHREAD implementation looks like following const
type TMyThread=class(TThread)
protected
public
end; // TMyThread constructor TMyThread.Create;
end; destructor TMyThread.Destroy;
end; procedure TMyThread.Execute;
except on e:Exception do
end;
end; procedure TMyThread.AddToProcess(Item:TObject);
end; procedure TMyThread.DoProcessData(Item:TObject);
end; procedure TMyThread.WinProc(var Message: TMessage);
end; Code explanation.The most part of the module is the same (only TMyThread
implementation is affected) - so here is only changes. Const section of the unit declares two constants - CM_DATA and CM_TERMINATE - message identifiers. Please note that their values are from the range that is intended for private application message. It's good way to avoid message id conflicts. TMyThread class inherited from TThread represents new thread. TmyThread.Execute creates window by calling AllocateHWnd function and enter the message loop. Terminated property should be set to TRUE to break the loop. All unprocessed messages will be processed by second PeekMessage loop. Then the window handle will be freed and thread finishes execution. Go To Page: 1 2
The copyright of the article Windows and message handling. Part 2 in Delphi Programming is owned by . Permission to republish Windows and message handling. Part 2 in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|