我想制作一个显示文本透明的静态控件的背景。经过2天的谷歌搜索后,我想出了这个:
class TLABEL : public TWINDOW {
private:
HINSTANCE hInst;
public:
static LRESULT CALLBACK SubclassCallback(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR userdata)
{
TLABEL* pThisWindow = (TLABEL*)userdata;
//look for messages that we want to process ourselves
switch (msg)
{
//make background transparent
case WM_CTLCOLORSTATIC:
{
HDC hDC = (HDC)wParam;
SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(0, 0, 0)); //text color black
MessageBox(NULL, L"WM_CTLCOLORSTATIC", L"Error!",MB_ICONEXCLAMATION|MB_OK);
return (LRESULT)GetStockObject(NULL_BRUSH);
}
case WM_ERASEBKGND:
{
return TRUE;;
}
//remove Subclass if window is destroyed
case WM_NCDESTROY:
{
RemoveWindowSubclass(pThisWindow->handle, &TLABEL::SubclassCallback, uIdSubclass);
return TRUE;
}
}
//deliver all other messages to the original callback-function
return DefSubclassProc(hWnd, msg, wParam, lParam);
}
//standard alignment left
explicit TLABEL(int nx, int ny, int nwidth, int nheight, HWND hParent)
{
hInst = GetModuleHandle(NULL); //i know this is a bad practice
handle = CreateWindowEx(WS_EX_TRANSPARENT, //background transparent
L"STATIC", L"", //class name + text
WS_CHILD | WS_VISIBLE | SS_LEFT, //styles
nx, ny, nwidth, nheight, //dimensions
hParent, NULL, hInst, NULL);
//subclass window to catch messages we want to process ourselves
SetWindowSubclass(this->handle, &TLABEL::SubclassCallback, 0, (DWORD_PTR)this);
}
不知怎的,SubclassCallback()函数从不接收WM_CTLCOLORSTATIC消息,但我知道该函数被调用,并且它接收WM_ERASEBKGND消息就好了。如果我在主窗口的消息处理程序中处理WM_CTLCOLORSTATIC消息它可以工作,不幸的是,这会消除为这样的静态控件创建单独的类所带来的所有好处
我没有找到任何提示,为什么WM_CTLCOLORSTATIC消息被发送到主窗口而不是我的静态控件,因为所有示例似乎都是这样做的。
我已经在WinXP-32机器上的VS2010 Express下编译了它