请解释下面这段MFC程序自动生成的代码的意思及作用,谢谢!

void CMyClockDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文

SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

// 使图标在工作区矩形中居中
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;

// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}

一下三行是该方法上面的说明。(是MFC自动生成的)
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
由此可知:条件IsIconic()是有必要的。
以上代码的意思就是:如果CWnd最小化了,那么就先获取设备上下文,然后用图表擦出背景,然后获得图表的宽和高,再获得最小化时的客户区矩形大小,通过int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;计算,然后在x,y出画图标m_hIcon.(由// Center icon in client rectangle注释可以知道是在最小化时的客户区中间画图标)否则直接调用父类的OnPaint重画对话框。追问

SendMessage(WM_ICONERASEBKGND, reinterpret_cast(dc.GetSafeHdc()), 0);
这个消息什么意思?
int x = (rect.Width() - cxIcon + 1) / 2;这个为什么加1
int cxIcon = GetSystemMetrics(SM_CXICON);
这个什么意思?

希望您能详细解答,谢谢

追答

The WM_ICONERASEBKGND message is sent to a minimized window when the background of the icon must be filled before painting the icon. A window receives this message only if a class icon is defined for the window; otherwise, WM_ERASEBKGND is sent. This message is not sent by newer versions of Windows.
以上是msdn里查到的关于WM_ICONERASEBKGND消息的说明,可知这个消息发送给一个最小化窗口,在绘制图表之前先填充图标背景。由此可知sendmessage就是要在绘制图标前先填充最小化窗口的背景。
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.

void CScanDlg::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
{
CDialog::OnPaint();
}
}
以上一段代码是VC6.0里自动生成的代码,由注释"// Center icon in client rectangle"可以知道,图标将会画在客户区的中间。int x = (rect.Width() - cxIcon + 1) / 2;这个式子是为了求出画图标时图标左上角x的坐标。假如客户区宽度为100,图标的宽度(cxIcon)为70,则x的值为15,则图标的宽度是从15到15+70=85像素位置,这个位置正好是客户区的中间位置。至于为什么要加1,其实并不需要细究,这个只是为了稍微精确点而已,如果不加1的话也就一两个像素的偏差,图片看上去也会是中间位置显示。
int cxIcon = GetSystemMetrics(SM_CXICON);
以上这个式子的意思就是获得图标的宽度。

温馨提示:答案为网友推荐,仅供参考