Nathaniel Smith
Nathaniel Smith

Reputation: 55

paint background in mfc

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;
    }    
};  

Upvotes: 2

Views: 2291

Answers (1)

sergiol
sergiol

Reputation: 4335

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.

Upvotes: 1

Related Questions