Threads in C++ builder [closed]

时光总嘲笑我的痴心妄想 提交于 2019-12-04 06:48:11

It might be simplier to just delay your logic until after the OnShow event has exited, without using a thread at all. For example:

const UINT WM_DO_WORK = WM_USER + 1;

void __fastcall TForm1::FormShow(TObject *Sender)
{
    PostMessage(Handle, WM_DO_WORK, 0, 0);
}

void __fastcall TForm1::WndProc(TMessage &Message)
{
    if (Message.Msg == WM_DO_WORK)
    {
        // do work here ...
    }
    else
        TForm::WndProc(Message);
}

If you really want to thread the code, you can do it like this:

class TMyThread : public TThread
{
protected:
    virtual void __fastcall Execute();
public:
    __fastcall TMyThread();
};

__fastcall TMyThread::TMyThread()
    : TThread(true)
{
    FreeOnTerminate = true;
    // setup other thread parameters as needed...
}

void __fastcall TMyThread::Execute()
{
    // do work here ...
    // if you need to access the UI controls,
    // use the TThread::Synchornize() method for that
}

void __fastcall TForm1::FormShow(TObject *Sender)
{
    TMyThread *thrd = new TMyThread();
    thrd->OnTerminate = &ThreadTerminated;
    thrd->Resume();
}

void __fastcall TForm1::ThreadTerminated(TObject *Sender)
{
    // thread is finished with its work ...
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!