VC6修改对话框颜色方法
在软件开发中,出于界面的美观或是别的目的我们需要修改对话框的颜色,这时我们可以通过如下方法来达到目的。
1、 修改App类中的InitInstance函数来改变应用程序中所有的对话框颜色
本方法所用函数为CWinApp类的成员函数SetDialogBkColor,关于SetDialogBkColor的详细说明请参见MSDN;使用例子如下:
BOOL CTestApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CSdfDlg dlg;
m_pMainWnd = &dlg;
//请注意下行的位置,一定要在dlg的DoModal函数之前
SetDialogBkColor(RGB(0,0,255),RGB(255,0,0));
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
注:此种方法将更改应用程序中所有对对话框的颜色
2、 在WM_PAINT消息(既OnPaint函数)中修改本对话框颜色
在Dlg类的WM_PAINT消息中修改本对话框颜色,既通过重载OnPaint函数来达到修改本对话框颜色的目的,使用例子如下:
void CTestDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
//通过如下红色代码来达到修改对话框颜色的目的
CRect rect;
CPaintDC dc(this);
GetClientRect(rect);
dc.FillSolidRect(rect,RGB(0,255,255)); //设置为绿色背景
CDialog::OnPaint();
}
}
3、 在WM_CTLCOLOR消息(既OnCtlColor函数)中修改本对话框颜色
本方法通过响应对话框的WM_CTLCOLOR消息来达到修改本对话框颜色,既通过重载OnCtlColor来达到此目的,使用例子如下:
HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
// TODO: Return a different brush if the default is not desired
if( nCtlColor == CTLCOLOR_DLG )
return m_rBrush; //返加绿色刷子
return hbr;
}
注:上面的m_rBrush为Cbrush类实例;可以在对话框中的OnInitDialog函数中创建本实例,如:m_rBrush.CreateSolidBrush(RGB(0, 255, 0));
说明:
上述方法均有各自的优缺点,如方法1将更改应用程序中所有对话框类的颜色,而方法2则可能带来对话框的闪动等。所以在具体应用中用户可以根据自己的需求选用相应的方法。