c++builder中截获TPanel的窗口信息(其他控件类似)

以默认方式新建一个工程, 窗体上放一个Panel,然后
在.h中增加:

private:
    TWndMethod OldPanelProc;
    void __fastcall NewPanelProc(Messages::TMessage &Message);

在.cpp中:

__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
   OldPanelProc = Panel1->WindowProc; //保存旧窗口函数
   Panel1->WindowProc = NewPanelProc; //设置新窗口函数

}
//---------------------------------------------------------------------------
void __fastcall TForm1::NewPanelProc(Messages::TMessage &Message)
{
    static TColor cl = clBlue;

    OldPanelProc(Message);   //执行默认动作

    switch (Message.Msg)
    {
    case WM_PAINT:
    {
        TRect rc = Panel1->ClientRect;
        TControlCanvas *cvs = new TControlCanvas;
        cvs->Control = Panel1;
        cvs->Font->Color = cl;
        cvs->Brush->Color = cl;

        cvs->FrameRect(rc);  //画边框

        cvs->Brush->Style = bsClear;

        //画文字
        DrawText(cvs->Handle, Panel1->Caption.c_str(),
            Panel1->Caption.Length(),
            &rc,
            DT_SINGLELINE|DT_CENTER|DT_VCENTER);


        delete cvs;
    }
    break;
    case WM_LBUTTONDOWN:
        cl = clGreen;   //鼠标按下时Panel颜色
        Panel1->Invalidate();
    break;
    case WM_LBUTTONUP:
        cl = clBlue;  //鼠标未按下时Panel颜色
        Panel1->Invalidate();
    break;
    default:
    break;
    }

}

在Form的OnDestroy事件中还原过来:
void __fastcall Form1::FormDestroy
{
    Panel1->WindowProc = OldPanelProc ;
}

你可能感兴趣的:(c++builder中截获TPanel的窗口信息(其他控件类似))