Kermia
Kermia

Reputation: 4221

Can i use the OnChange event of a Editbox to handle Threads?

Is it a right way to get responses from a Thread through OnChange event of aEditbox by calling a synchronize mothod that changes value of Editbox?

Something like this :

//Extra Thread
procedure HThread.Execute;
begin
    Synchronize(CallGUI);
end;

procedure HThread.CallGUI;
begin
  Edit.Text = 'Hello';
end;


//Main Thread
procedure Main;
begin
  Tr := HThread.Create(true);
  Tr.Edit := Form1.Edit1;
  Tr.Resume;
end;

procedure TForm1.Edit1Change(Sender: TObject);
begin
  ShowMessage('Response from extra thread :' + Edit1.text);
end;

Upvotes: 0

Views: 329

Answers (3)

Cosmin Prund
Cosmin Prund

Reputation: 25678

Your use of TEdit is troublesome, for a couple of reasons:

  • It looks like you're using the TEdit as a place for data transfer from the thread (the reliance on the OnChange event handler makes me think some more processing is required, the TEdit isn't used as a simple "output area"). GUI elements should never be used for data storage, for countless reasons ranging from performance to OOP encapsulation and relying on algorithms outside your control.
  • Relying on the OnChange event handler to fire when you programatically change the text is relying on implementation details of TEdit. What if Microsoft decides not to fire the OnChange event if the change was made programatically? Or Embarcadero decides to conditionally not surface it since the programmer doesn't need to be notified he just changed that value?

Other then that, your use of Syncronize() will probably work, ie "you can use it", but I'd say it's not a good idea. I'd like to suggest a better solution but can't do that, because I don't know exactly what you're trying to do. If all you want to do is force OnChange to be fired, then keep your code.

Upvotes: 3

Matthias Alleweldt
Matthias Alleweldt

Reputation: 2453

Assuming you change the EditBox text value in a procedure called via Synchronize() from a thread, the assigned OnChange event will be executed in the GUI thread. This will work with no problem but will halt your thread unitl the event is processed.

Upvotes: 2

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29993

Changing something in UI via Synchronize() is a correct way, if you mean that. I'm not sure I understood the rest of your question though.

Upvotes: 0

Related Questions