WM_POWERBROADCAST 只发送到顶级窗口,从不发送到子窗口。所以,你有几个选择:
- 让您的 WinControl 使用
TApplication.HookMainWindow() 方法拦截发送到隐藏的TApplication 窗口的消息。当你的 WinControl 被销毁时,一定要移除钩子。
__fastcall TMyControl::TMyControl(TComponent *Owner)
: TWinControl(Owner)
{
Application->HookMainWindow(&AppHook);
}
__fastcall TMyControl::~TMyControl()
{
Application->UnhookMainWindow(&AppHook);
}
bool __fastcall TMyControl::AppHook(TMessage &Message)
{
if (Message.Msg == WM_POWERBROADCAST)
{
// ...
}
return false;
}
- 拦截发送到
TForm 窗口的消息,通过将MESSAGE_MAP 应用到Form 类,或者通过覆盖Form 的虚拟WndProc() 方法,然后让From 将消息转发到您的WinControl .
BEGIN_MESSAGE_MAP
...
VCL_MESSAGE_HANDLER(WM_POWERBROADCAST, TMessage, WMPowerBroadcast);
END_MESSAGE_MAP(inherited);
...
void __fastcall TForm1::WMPowerBroadcast(TMessage &Message)
{
inherited::Dispatch(&Message);
MyControl->Perform(Message.Msg, Message.WParam, Message.LParam);
}
或者:
void __fastcall TForm1::WndProc(TMessage &Message)
{
inherited::WndProc(Message);
if (Message.Msg == WM_POWERBROADCAST)
MyControl->Perform(Message.Msg, Message.WParam, Message.LParam);
}
- 让您的 WinControl 使用 RTL 的
AllocateHWnd() 函数创建自己的隐藏顶层窗口。
private:
HWND FPowerWnd;
void __fastcall PowerWndProc(TMessage &Message);
...
__fastcall TMyControl::TMyControl(TComponent *Owner)
: TWinControl(Owner)
{
FPowerWnd = AllocateHWnd(&PowerWndProc);
}
__fastcall TMyControl::~TMyControl()
{
DeallocateHWnd(FPowerWnd);
}
void __fastcall TMyControl::PowerWndProc(TMessage &Message)
{
if (Message.Msg == WM_POWERBROADCAST)
{
// ...
}
else
{
Message.Result = ::DefWindowProc(FPowerWnd, Message.Msg, Message.WParam, Message.LParam);
}
}