VC++ 设置控件显示文本的前景色、背景色以及字体

时间:2023-11-25 23:00:56

在每个控件开始绘制之前,都会向其父窗口发送WM_CTLCOLOR通告消息,在该消息的处理函数中,可以设置控件显示文本的前景色、背景色以及字体。该消息处理函数还要求返回一个画刷的句柄,用于在控件具体的绘制之前擦除其客户区。

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

{

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

  // TODO:  Return a different brush if the default is not desired

  return hbr;

}

1、pDC:控件的上下文对象。

2、pWnd:控件对象指针,可以指定具体某个控件的属性。

3、nCtlColor:Color Types。

Color Types:

#define CTLCOLOR_MSGBOX 0
#define CTLCOLOR_EDIT 1
#define CTLCOLOR_LISTBOX 2
#define CTLCOLOR_BTN 3
#define CTLCOLOR_DLG 4
#define CTLCOLOR_SCROLLBAR 5
#define CTLCOLOR_STATIC 6
#define CTLCOLOR_MAX 7

#define COLOR_SCROLLBAR 0
#define COLOR_BACKGROUND 1
#define COLOR_ACTIVECAPTION 2
#define COLOR_INACTIVECAPTION 3
#define COLOR_MENU 4
#define COLOR_WINDOW 5
#define COLOR_WINDOWFRAME 6
#define COLOR_MENUTEXT 7
#define COLOR_WINDOWTEXT 8
#define COLOR_CAPTIONTEXT 9
#define COLOR_ACTIVEBORDER 10
#define COLOR_INACTIVEBORDER 11
#define COLOR_APPWORKSPACE 12
#define COLOR_HIGHLIGHT 13
#define COLOR_HIGHLIGHTTEXT 14
#define COLOR_BTNFACE 15
#define COLOR_BTNSHADOW 16
#define COLOR_GRAYTEXT 17
#define COLOR_BTNTEXT 18
#define COLOR_INACTIVECAPTIONTEXT 19
#define COLOR_BTNHIGHLIGHT 20

#define COLOR_3DDKSHADOW 21
#define COLOR_3DLIGHT 22
#define COLOR_INFOTEXT 23
#define COLOR_INFOBK 24

#define COLOR_HOTLIGHT 26
#define COLOR_GRADIENTACTIVECAPTION 27
#define COLOR_GRADIENTINACTIVECAPTION 28

#define COLOR_MENUHILIGHT 29
#define COLOR_MENUBAR 30

#define COLOR_DESKTOP COLOR_BACKGROUND
#define COLOR_3DFACE COLOR_BTNFACE
#define COLOR_3DSHADOW COLOR_BTNSHADOW
#define COLOR_3DHIGHLIGHT COLOR_BTNHIGHLIGHT
#define COLOR_3DHILIGHT COLOR_BTNHIGHLIGHT
#define COLOR_BTNHILIGHT COLOR_BTNHIGHLIGHT

根据这些Color Types可以指定不同类型控件的属性,常用属性设置有

pDC->SetTextColor(RGB(255, 0, 0));    //设置文本前景色

pDC->SetBkColor(RGB(255, 255, 255));  //设置文本背景色

pDC->SetBkMode(TRANSPARENT);          //TRANSPARENT或OPAQUE

最后要返回自定义HBRUSH

例子:

HBRUSH CShowVideoDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
  HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);

  // TODO: Change any attributes of the DC here
  HBRUSH b;
  if(nCtlColor == CTLCOLOR_STATIC)
  {
    switch(pWnd->GetDlgCtrlID())
    {
      case IDC_NODE_NAME:
      {
        pDC->SetTextColor(0x228B22);
        pDC->SetBkColor(RGB(0x8D, 0xB6, 0XCD));

        b = CreateSolidBrush(RGB(0x8D, 0xB6, 0XCD));
      }
      break;
      case IDC_STATIC_DisPlay:
      {
        pDC->SetBkColor(RGB(0, 0, 0));

        b = CreateSolidBrush(RGB(0, 0, 0));
      }
      break;
    }
  }
  else if(nCtlColor == COLOR_MENU)
  {
    if(pWnd->GetDlgCtrlID() == IDR_PLAY_MENU)
    {
      pDC->SetTextColor(0x228B22);
      pDC->SetBkColor(RGB(0x8D, 0xB6, 0XCD));

      b = CreateSolidBrush(RGB(0x8D, 0xB6, 0XCD));
    }
  }

  return b;
  // TODO: Return a different brush if the default is not desired
  //return hbr;
}