2
votes

I am experimenting with painting the background of a window in c++ using the MFC library. It is mandated that i use this framework because I am working on an MFC application. I have tried several different methods but cannot get it to work. So i recently opened a blank project and just want to figure out how to paint the background but it is not working. Any help would be great. Here is my code...

class CExerciseApp : public CWinApp
{   
     //a pointer to our window class object
     Basic_Window *bwnd; 

     BOOL InitInstance()
     {  
         bwnd = new Basic_Window();
         m_pMainWnd = bwnd;
         bwnd->ShowWindow(1);

         HWND hWnd = GetActiveWindow();

         CRect drawing_area;
         GetClientRect(hWnd, &drawing_area);

         CBrush newBrush;
         newBrush.CreateSolidBrush(RGB(255,255,255));

         CDC* dc = bwnd->GetDC();
         dc->FillRect(&drawing_area, &newBrush);
         bwnd->RedrawWindow();
         return TRUE;
    }    
};  
1
Should I post the WM_ERASEBKGND message before calling FillRect? - Nathaniel Smith
You don't post/send WM_ERASEBKGND, the system will do it when appropriate. You should rather override CWnd::OnEraseBkgnd and do your background painting there. That's really all there is to it. - IInspectable
What is a Basic_Window? That is not an MFC window. You need to put all your painting code like the FillRect() into the paint procedure of your Basic_Window, not just paint it in InitInstance, which is only called once. It isn't working because as soon as another window (yours or another application's) covers it and then uncovers it, your painting does not occur again and is therefore gone. - David Ching
But if a painting operation is done in InitInstance, shouldn - Nathaniel Smith

1 Answers

1
votes

From my own post https://stackoverflow.com/a/22875542/383779 , I can guarantee I had made that work. I used that approach for implementing themes/skins on a commercial application.

You need to add a OnCtlColor method to your Basic_Window class. In your .h file, add to the Basic_Window class:

const CBrush m_BackgroundBrush;

and

afx_msg HBRUSH OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor);

In .cpp file the constructor will initialize the new variable

Basic_Window::Basic_Window()
: m_BackgroundBrush(RGB(255,255,255))
{
//...
}

and implement

HBRUSH Basic_Window::OnCtlColor( CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    if(some_exception)
        return __super::OnCtlColor( pDC, pWnd, nCtlColor);

    return (HBRUSH) m_BackgroundBrush.GetSafeHandle();
}

some_exception here means a situation where you will want the default behavior, instead of your own painting. Maybe it is a certain type of control, and for that exists the nCtlColor parameter.

Do not forget to add ON_WM_CTLCOLOR() to your message map.