在Dialog对话框程序中,改变控件颜色和背景色一直用的是重载WM_CTLCOLOR(不带=号的),在重载函数中使用CDC::SetBkColor(),返回缺省的 HBRUSH hbr 来进行。这种方法对Static和Edit框很有效。但是用在ListBox框上面的时候,发现控件靠近左边或者右边的地方无论怎样调节大小,都有一条细细的白线去不掉。在网上查了很多资料,看见了很多较为复杂的方法,包括继承(SubClass) Clistbox类。这些方法都很好,但是如果一个Dialog里面有几十个ListBox,那么管理这些继承类将不是一件轻松的工作。其实,WM_CTLCOLOR的重载函数OnCtlColor中有两种方法来实现对控件背景的修改。
一种是pDC->SetBkColor()的方法,但是需要设置pDC->SetBkMode(TRANSPARENT),并且返回缺省的HBRUSH hbr
另外一种是设置pDC->SetBkMode(OPAQUE),在函数末尾返回一个在类的.h文件中定义的CBrush m_Brush变量对ListBox,需要使用第二种方法。因为OnCtlColor函数带了一个 UINT nCtlColor变量,有如下含义:
nCtlColor
Contains one of the following values, specifying the type of control:
CTLCOLOR_BTN Button control
CTLCOLOR_DLG Dialog box
CTLCOLOR_EDIT Edit control
CTLCOLOR_LISTBOX List-box control
CTLCOLOR_MSGBOX Message box
CTLCOLOR_SCROLLBAR Scroll-bar control
CTLCOLOR_STATIC Static control 我们只需要在函数中写出这样的代码:if (nCtlColor == CTLCOLOR_LISTBOX)
{
pDC->SetBkMode(TRANSPARENT);
return m_Brush; // m_Brush defined in .h file,m_Brush.CreateSolidBrush
// in InitDialog function
}
else
{
pDC->SetBkMode(OPAQUE);
pDC->SetBkColor(RGB(255,0,0));(
return hbr;
}希望能够给大家带来帮助。但是我目前还是不明白为什么只有第二种方法才能完全的画ListBox的背景
一种是pDC->SetBkColor()的方法,但是需要设置pDC->SetBkMode(TRANSPARENT),并且返回缺省的HBRUSH hbr
另外一种是设置pDC->SetBkMode(OPAQUE),在函数末尾返回一个在类的.h文件中定义的CBrush m_Brush变量对ListBox,需要使用第二种方法。因为OnCtlColor函数带了一个 UINT nCtlColor变量,有如下含义:
nCtlColor
Contains one of the following values, specifying the type of control:
CTLCOLOR_BTN Button control
CTLCOLOR_DLG Dialog box
CTLCOLOR_EDIT Edit control
CTLCOLOR_LISTBOX List-box control
CTLCOLOR_MSGBOX Message box
CTLCOLOR_SCROLLBAR Scroll-bar control
CTLCOLOR_STATIC Static control 我们只需要在函数中写出这样的代码:if (nCtlColor == CTLCOLOR_LISTBOX)
{
pDC->SetBkMode(TRANSPARENT);
return m_Brush; // m_Brush defined in .h file,m_Brush.CreateSolidBrush
// in InitDialog function
}
else
{
pDC->SetBkMode(OPAQUE);
pDC->SetBkColor(RGB(255,0,0));(
return hbr;
}希望能够给大家带来帮助。但是我目前还是不明白为什么只有第二种方法才能完全的画ListBox的背景
楼主参考一下
給ListBox設置背景圖片Declare Function ReleaseDC Lib "user32" (ByVal hWnd As Long, ByVal hdc As Long) As Long
Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
Declare Function BitBlt Lib "gdi32" (ByVal hDestDC As Long, ByVal x As Long, ByVal y _
As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, _
ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) As Long
Const SRCCOPY = &HCC0020
Const SRCPAINT = &HEE0086
Const SRCAND = &H8800C6
Const SRCINVERT = &H660046Private Sub Form_Load()
Dim I As Integer
Picture1.Picture = LoadPicture("D:\My Documents\My Pictures\cd.jpg")
Picture1.ScaleMode = 3 '像素單位
List1.ForeColor = vbRed
For I = 1 To 10
List1.AddItem I
Next I
End SubPrivate Sub List1_Click()
SetBack
End SubFunction SetBack()
Dim mhDC As Long
mhDC = GetDC(List1.hWnd)
Call BitBlt(mhDC, 0, 0, List1.Width, List1.Height, Picture1.hdc, 0, 0, SRCAND)
Call ReleaseDC(List1.hWnd, mhDC)
End Function