Lo que necesita hacer es configurar un bucle de mensajes en su hilo, y usar AllocateHWnd en su hilo principal para enviar mensajes hacia adelante y hacia atrás. Es bastante simple.
En su hilo de ejecutar la función de tener lo siguiente:
procedure TMyThread.Execute;
begin
// this sets up the thread message loop
PeekMessage(LMessage, 0, WM_USER, WM_USER, PM_NOREMOVE);
// your main loop
while not terminated do
begin
// look for messages in the threads message queue and process them in turn.
// You can use GetMessage here instead and it will block waiting for messages
// which is good if you don't have anything else to do in your thread.
while PeekMessage(LMessage, 0, WM_USER, $7FFF, PM_REMOVE) do
begin
case LMessage.Msg of
//process the messages
end;
end;
// do other things. There would probably be a wait of some
// kind in here. I'm just putting a Sleep call for brevity
Sleep(500);
end;
end;
Para enviar un mensaje a su hilo, hacer algo como lo siguiente:
PostThreadMessage(MyThread.Handle, WM_USER, 0, 0);
En el lado del hilo principal de las cosas, establecer hasta un identificador de ventana utilizando AllocateHWnd (en la unidad Clases), pasándole un método WndProc. AllocateHWnd es muy ligero y es fácil de usar:
TMyMessageReciever = class
private
FHandle: integer;
procedure WndProc(var Msg: TMessage);
public
constructor Create;
drestructor Destroy; override;
property Handle: integer read FHandle;
end;
implementation
constructor TMyMessageReciever.Create;
begin
inherited Create;
FHandle := Classes.AllocateHWnd(WndProc);
end;
destructor TMyMessageReciever.Destroy;
begin
DeallocateHWnd(FHandle);
inherited Destroy;
end;
procedure TMyMessageReciever.WndProc(var Msg: TMessage);
begin
case Msg.Msg of
//handle your messages here
end;
end;
y enviar mensajes, ya sea con SendMessage
, que bloqueará hasta que el mensaje haya sido manipulado, o PostMessage
la que lo hace de forma asíncrona.
Espero que esto ayude.
Es posible que desee echar un vistazo a ['AllocateHWnd'] (http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Classes_AllocateHWnd.html). –
@Sertac Akyuz, lo siento, he secuestrado su sugerencia involuntariamente, solo me di cuenta después de escribir mi propia respuesta :-( –
La desventaja de AllocateHwnd es que no es seguro. Por supuesto, esto se puede solucionar –