使用WinAPI创建具有透明背景的文本标签

时间:2011-08-30 14:53:00

标签: c++ winapi transparency

是否可以仅使用WinAPI命令在窗口中创建具有透明背景的标签?

我正在尝试将图像添加到对话框窗口,该窗口将用作背景图像,然后在该图像上显示文本。到目前为止,我所尝试的所有内容都在背景图像的顶部显示了文本标签,并在其周围绘制了一个灰色矩形。

这是我目前为止的代码示例(显示对话框的整个消息处理程序):

INT_PTR CALLBACK OfferWindowProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{       
    HWND hWndBackground;
    HWND hWndLabel;
    HBRUSH hLabelBackColour = NULL;
      HFONT hfFont;
      HWND hWndTitleLabel;
    HDC hdcStatic = NULL;

    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:             

        //Load the background image
        HANDLE hBitmap;
        hBitmap = LoadImage(NULL, L"C:\\Users\\DavidHall\\Documents\\bg.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
        if (hBitmap != NULL)
        {
            hWndBackground = CreateWindow(L"STATIC", L"image box", WS_CHILD | WS_VISIBLE | SS_BITMAP, 0, 0, 100, 100, hDlg, (HMENU) 2000, NULL, NULL);          
            SendMessage(hWndBackground, STM_SETIMAGE, IMAGE_BITMAP, LPARAM(hBitmap));
        }           

        // Create the label using CreateWindowEx
        hfFont = CreateFont(20, 0, 0, 0, fontWeight, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY,
            DEFAULT_PITCH, L"Verdana");

        hWndTitleLabel = CreateWindowEx( WS_EX_TRANSPARENT, L"STATIC", L"", WS_CHILD | WS_VISIBLE | SS_LEFT | WS_SYSMENU , xPos, yPos, width, height, hwnd, (HMENU) id, hInst, NULL);           

        SendMessage(hWndTitleLabel, WM_SETTEXT, NULL, (LPARAM) labelText.c_str());

        SendMessage(hWndTitleLabel, WM_SETFONT, (WPARAM)hfFont, NULL);  

        return (INT_PTR)TRUE;   

    case WM_CLOSE:
        EndDialog(hDlg, LOWORD(wParam));    

        // Delete the brush - is that correct?
        DeleteObject(hLabelBackColour);
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    default:
        break;
    }
    return (INT_PTR)FALSE;
}

我尝试了各种各样的组合,包括:

  • SetLayeredWindowAttributes
  • SetBkMode(hdc, TRANSPARENT)
  • 处理WM_CTLCOLORSTATIC消息

2 个答案:

答案 0 :(得分:7)

我发现了一些似乎有效的东西,但由于我对纯WinAPI编程很陌生,这可能是非常糟糕的做法而且我不知道!

我正在处理WM_CTLCOLORSTATIC消息,如下所示:

case WM_CTLCOLORSTATIC:

    hdcStatic = (HDC) wParam; 
    SetTextColor(hdcStatic, RGB(0,0,0));    
    SetBkMode (hdcStatic, TRANSPARENT);

    return (LRESULT)GetStockObject(NULL_BRUSH);

这使我的标签出现在我的图像上,并带有透明背景。

答案 1 :(得分:0)

我无法发表评论,但我认为你应该看看Chris Becke的答案:Win32 transparent controls on all versions of Windows,它对我有用,我甚至不需要打电话给 InvalidateRect 。我希望这会有用。克里斯的答案需要pattern brush, look in this answer