如何改变ClistCtrl的背景色

……在MFC编程中像button,static ,dialog 等都可以在窗体的OnCtrlColor(……)中进行修改而达到设置其背景色

然而ClistCtrl 在这种情况下却行不通,下面我来给大家介绍一种解决方法:

(1)重新从CListCtrl派生出一个子类:如CBitmapList

在后在:其.h文件如下:

#pragma once
#include "afxcmn.h"

class CBitmapList :
 public CListCtrl
{
public:
 CBitmapList(void);
 ~CBitmapList(void);
public:
 //afx_msg OnSelectChange();
 //afx_msg OnScroll();
private: 
 CBitmap  m_bitmap; // back bitmap of the control
 CBrush backBrush ;
public:
 afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
 afx_msg BOOL OnEraseBkgnd(CDC* pDC);
 //  the last statement cannot be omitted
 DECLARE_MESSAGE_MAP()

};
(2)在.cpp文件中添加消息映射:

如下所示:

BEGIN_MESSAGE_MAP( CBitmaplist , CListCtrl)

  ON_WM_CTLCOLOR()
 ON_WM_ERASEBKGND()

END_MESSAGE_MAP()

(3)实现函数:

HBRUSH CBitmapList::CtlColor(CDC* pDC, UINT nCtlColor)
{

 // create brush
 backBrush.CreateStockObject( HOLLOW_BRUSH );
 // set teh back mode as transparent
 pDC->SetBkMode( TRANSPARENT );
 // Set Text Color
 pDC->SetTextColor( RGB(120,0,0) );

 return backBrush;
}

BOOL CBitmapList::OnEraseBkgnd(CDC* pDC)
{
 CDC MemDc;
 // create compatible device
 MemDc.CreateCompatibleDC( pDC );
 // select the object to the device
 MemDc.SelectObject( &m_bitmap );
 // the bitmap struct to hold the bitmap information
 BITMAP mapInfo;
 // to get bitmap information
 m_bitmap.GetBitmap( &mapInfo);

 CRect rc;
 // to get control's width and height
 GetClientRect( &rc);
 // to draw the bmp on the specify position
 pDC->StretchBlt( 0,0, rc.Width() ,rc.Height() ,
  &MemDc ,0,0,mapInfo.bmWidth ,
  mapInfo.bmHeight ,SRCCOPY );
 // to releave dc
 ReleaseDC ( &MemDc );
 return TRUE;
}

 (4)如何使用 自己的类:

首先按通常方法绘画自己的相应控件(CListCtrl)到窗体上,然后对该控件添加变量,如:m_list ,类型为control,但类为自己派生的类这里是CBitmapList.

最后还要在Dialog的Oninitial(^)中添加以下代码:

m_list.SubclassDlgItem( IDC_LIST2 ,this );// 主义必须是该函数的开始代码,要不然会出现非法操作警告

这样子,ClistCtrl控件显示的就是自己想要的背景了哦……

原文地址:https://www.cnblogs.com/For-her/p/3557055.html