2012-07-24 78 views
6

我是C++ builder的新手,对线程不熟悉我希望有人可以发表一个示例或指向正确的方向。C++ builder中的线程

我有一个窗体,在C++ builder中加载formShow()函数。它做我希望我的程序要做的事情,但只有在它之后才会显示实际的表单。

为此我需要线程的形式和程序的后台运行。任何人都可以帮助我吗?

回答

8

OnShow事件退出之前,可能只是简单地延迟逻辑,而不使用线程。例如:

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); 
} 

如果你真的想线程的代码,你可以做这样的:

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 ... 
}