要在 C++ Builder 中實作透明視窗,需覆寫 CreateParams 設定擴充樣式,並處理 WM_ERASEBKGND 訊息避免背景重繪。
class TYourForm : public TForm
{
private:
void __fastcall WMNC(TMessage &Message);
public:
__fastcall TYourForm(TComponent *Owner);
BEGIN_MESSAGE_MAP
VCL_MESSAGE_HANDLER(WM_ERASEBKGND, TMessage, WMNC);
END_MESSAGE_MAP(TForm);
protected:
virtual void __fastcall CreateParams(TCreateParams &Params);
};
void __fastcall TYourForm::CreateParams(TCreateParams &Params)
{
TForm::CreateParams(Params);
Params.ExStyle |= WS_EX_TRANSPARENT; // 設定透明擴充樣式
}
void __fastcall TYourForm::WMNC(TMessage &Message)
{
// 設定背景模式為不透明,避免閃爍
SetBkMode(GetWindowDC(this->Handle), OPAQUE);
ReleaseDC(this->Handle, GetWindowDC(this->Handle));
Message.Result = 1; // 表示已處理背景擦除
}
WS_EX_TRANSPARENT 讓視窗成為透明視窗,滑鼠事件會穿透給下層視窗。WM_ERASEBKGND 並回傳 1,告訴系統背景已自行處理,減少閃爍。