본문 바로가기
Windows/MFC 강좌 & Tips

[다이얼로그 배경색 지우기] OnEraseBkgnd 와 OnCtlColor

by 미티치 2020. 8. 8.

 

다이얼로그의 배경 색을 바꾸는 예제는 아래와 같다

BOOL MainWnd::OnEraseBkgnd(CDC* pDC)

{

    CRect r;

    GetClientRect(r);

 

    // 배경색을 파란색으로 변경한다. 흰색은 RGB(255,255,255)

    pDC->FillSolidRect(r, RGB(0,0,255));

    

    return TRUE;

}

 

 

문제는 OnCtlColor 에서도 마지막 매개변수인 nCtlColor 값을 CTLCOLOR_DLG 로 설정하면 다이얼로그 배경색을 바꿀 수 있는데, 

 

  • OnEraseBkgnd 함수를 호출하는 메시지 WM_ERASEBKGND 의 정의 : 창 배경을 지워야 함을 나타냅니다.

  • OnCtlColor 함수를 호출하는 메시지 WM_CTLCOLOR 의 정의 : 컨트롤이 그려지려고 함을 나타냅니다.

 

MFC 프로젝트 위자드에서 메시지에 대한 정의가 위와 같이 되어있다.

사실  OnCtlColor 를 통해서 다이얼로그의 배경색을 지정할 수는 있으나, 윈도우의 메시지 정의는 위와 같으므로

배경색은 OnEraseBkgnd 에서 수정하고, 컨트롤의 색이나 폰트 지정은 OnCtlColor에서 지정하는 편이 좋을 것 같다.

 

 

 


 

 

예제는 아래와 같음

// This OnCtlColor handler will change the color of a static control

// with the ID of IDC_MYSTATIC. The code assumes that the CPenWidthsDlg

// class has an initialized and created CBrush member named m_brush.

// The control will be painted with red text and a background

// color of m_brush.

HBRUSH CPenWidthsDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)

{

   // Call the base class implementation first! Otherwise, it may

   // undo what we're trying to accomplish here.

   HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

 

   // Are we painting the IDC_MYSTATIC control? We can use

   // CWnd::GetDlgCtrlID() to perform the most efficient test.

   if (pWnd->GetDlgCtrlID() == IDC_MYSTATIC)

   {

      // Set the text color to red

      pDC->SetTextColor(RGB(255, 0, 0));

 

 

      // Set the background mode for text to transparent

      // so background will show thru.

      pDC->SetBkMode(TRANSPARENT);

 

 

      // Return handle to our CBrush object

      hbr = m_brush;

   }

 

   return hbr;

}