开发者

Send a message directly from a thread to an object without using the main form

I'm using a 3rd party library that uses a lot of threads.

I've just started using messages to communicate back to the main thread from a thread. It's all working, but using SendMessage the way I describe below seems cumbersome because the main form has to dispatch all the messages. Is there a way to send a message directly to a frame or object, without depending on the main form?

At program startup:

 MyMessageNumber1 :=  RegisterWindowMessage('MyUniqueID1');
 MyMessageNumber2 :=  RegisterWindowMessage('MyUniqueID2');

When sending a message wit开发者_C百科hout any data, I do:

 SendMessage(Application.MainForm.Handle,  MyMessageNumber1) 

My main form has this:

procedure WndProc(var Message: TMessage); override;
if (Message.Msg = MyMessageNumber1)
  ... call a frame or other object's method that handles this particular message
else if (Message.Msg = MyMessageNumber2) then
  ... call another ....
else
  inherited;

In summary: the above WndProc has to know far more than I'd prefer about all the messages and who to dispatch them to.

How can I send a message directly from a thread in a way that any object can receive it?

All of these messages have no data associated with them. (We'll get to that some other day!) :-)

TIA


Yes you can. You can use AllocateHWND to allocate a window handle in any object. This handle can be used to send messages to.

But you problem may lie in the SendMessage. If you use PostMessage instead of SendMessage, the call will return immediately. PostMessage does not wait for a message to be handled. So if you don't need the message result, and you don't need to send references to thread-data, you can just use PostMessage.


Other forms and frames have handles as well, and you can define message-handling methods on them, then post the message directly to the form or frame. (Or control, for that matter, if you're building your own custom controls.)

See http://docwiki.embarcadero.com/RADStudio/en/Declaring_a_New_Message-handling_Method for an overview on setting up message-handling methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜