How to make a CStatic control (MFC) transparent?

2019-02-17 21:13发布

My application has a start dialog with an image which fills the whole dialog. Additionaly there is a CStatic control, which displays some variable information for the user. I made the CStatic control transparent with following code:

HBRUSH CStartbildDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    if(pWnd->GetDlgCtrlID() == IDC_STATIC_INFO)
    {
        pDC->SetBkMode(TRANSPARENT);
        return reinterpret_cast<HBRUSH>(::GetStockObject(NULL_BRUSH));
    }
    else
        return CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
}

When I change the text of the static control with GetDlgItem(IDC_STATIC_INFO)->SetWindowText, the new text overlaps the old text (the old text is not deleted). I have tried to repaint the background befor calling SetWindowText image with GetDlgItem(IDC_STATIC_BILD)->Invalidate(), but then no info text is shown (neither the old nor the new).

Do you know how I can make the static control transparent, so that I also can override it with a new text?

Thanks for your help!

Solution: Method 2 (adapted) from the codeproject-link from Sanja worked for me.

GetDlgItem(IDC_STATIC_INFO)->SetWindowText(tmp);
CRect rect;
GetDlgItem(IDC_STATIC_INFO)->GetWindowRect(&rect);
ScreenToClient(&rect);
InvalidateRect(&rect);
UpdateWindow();

2条回答
甜甜的少女心
2楼-- · 2019-02-17 21:41

Hi you can find transparent static sample here

查看更多
叛逆
3楼-- · 2019-02-17 21:52

This answer is related to the Windows API rather than MFC framework, but the concepts translate easilly:

Correct way to do transparent buttons in WINAPI

Your problem is that achieving transparent controls using Win32 native controls conflicts with achieving flicker free controls when repainting occurs.

查看更多
登录 后发表回答