MFC SDI: How do I create transparent SDI views?
Q: How do I create transparent SDI views?
A: One can make a the view of an MFC application transparent by handling 'CView::OnEraseBkgnd()' function and returning 'FALSE' instead of the default 'CView::OnEraseBkgnd()' call.
<br>
Code:
BOOL CTransparentView::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
return FALSE;
// return CView::OnEraseBkgnd(pDC);
}
But this will not give a real transparent window, since the original view background will be dragged along while moving the application window. To overcome this, I have handled 'OnMove()' and 'OnSize()' functions of 'CMainFrame' class to update the view to reflect the real background, by repainting the view each time the application window is moved / sized.
<br>
Code:
void CMainFrame::OnMove(int x, int y)
{
CFrameWnd::OnMove(x, y);
// TODO: Add your message handler code here
RepaintView();
}
void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
CFrameWnd::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
RepaintView();
}
I have defined a function 'RepaintWindow()' as part of the 'CMainFrame' class and implemented to repaint the view with correct background information.
<br>
Code:
void CMainFrame::RepaintView()
{
// Gets current view
CView* pView = GetActiveView();
if (pView) // Valid view
{
// Hides view to get background
ShowWindow(SW_HIDE);
// Gets desktop device context
HDC hDC = ::GetDC(NULL);
if (hDC) // Valid device context handle
{
// Get clients rectangle in screen coordinates
CRect Rect;
pView->GetClientRect(Rect);
pView->ClientToScreen(Rect);
// Gets device context for current view
CClientDC DC(pView);
// Pastes background to view
::BitBlt(DC.m_hDC, 0, 0, Rect.Width(), Rect.Height(),
hDC, Rect.left, Rect.top, SRCCOPY);
// Releases desktop device context
::ReleaseDC(NULL, hDC);
}
// Shows view with right background info
ShowWindow(SW_SHOW);
}
}
At present, this is implemented for SDI application. With little modification (for updating all views), this methodology can be extended for MDI applications as well.
<br><br><br>