I have a simple Delphi program that I'm working on, in which I am attempting to use threading to separate the functionality of the program from its GUI, and to keep the GUI responsive during more lengthy tasks, etc. Basically, I have a 'controller' TThread, and a 'view' TForm. The view knows the controller's handle, which it uses to send the controller messages via PostThreadMessage. I have had no problem in the past using this sort of model for forms which are not the main form, but for some reason, when I attempt to use this model for the main form, the message loop of the thread just quits.
Here is my code for the threads message loop:
procedure TController.Execute;
var
Msg : TMsg;
begin
while not Terminated do begin
if (Integer(GetMessage(Msg, hwnd(0), 0, 0)) = -1) then begin
Synchronize(Terminate);
end;
TranslateMessage(Msg);
DispatchMessage(Msg);
case Msg.message of
// ...call different methods based on message
end;
end;
end;
To set up the controller, I do this:
Controller := TController.Create(true); // Create suspended
Controller.FreeOnTerminate := True;
Controller.Resume;
For processing the main form's messages, I have tried using both Application.Run and the following loop (immediately after Controller.Resume)
while not Application.Terminated do begin
Application.ProcessMessages;
end;
I've run stuck here - any help would be greatly appreciated.
beginon the same line as thedoor thethenbefore it. That's considered good style in C, but in Delphi most of us prefer to put it on its own line so we can line upbeginandendpairs visually.TController.Execute, as soon as I step overGetMessage, no matter what I pass as the hwnd, it just doesn't keep going through the loop. It doesn't execute any statements after the loop, it just inexplicably stops. And what is even more confusing is that I see no indication that the thread itself has actually died.Synchronise()? If there is no message loop running, it may just fail. Also, which version of Delphi are you using?beginon its own line is visual noise. The indentation alone tells all that's needed. Stash the noise at the end of the line so it's out of the way.