Use the drawing handle HDC to draw in the client area, non-client area, and temporary client area

The first thing to know about a form is what is the client area and what is the non-client area. For example the following form:


The client area refers to the white area enclosed by the red frame.

The non-client area refers to: the entire form including the blue title bar, blue border, and white area.


1. Client area drawing: WM_PAINT is the client area display update message. All client area drawings must be drawn when this message is called back, that is, in the OnPaint() function, starting with BeginPaint() and ending with EndPaint().

void CClientDrawDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for drawing

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

		// Center the icon in the workspace 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
	{
		PAINTSTRUCT ps;
		//Get the drawing handle associated with the client area
		HDC hdc = ::BeginPaint(m_hWnd,&ps);

		Rectangle(hdc,0,0,40,40);

		Rectangle(hdc,80,80,120,120);

		MoveToEx(hdc,20,20,NULL);

		LineTo(hdc,100,100);
		//End client area drawing, paired with ::BeginPaint
		::EndPaint(m_hWnd,&ps);

		CDialogEx::OnPaint();
	}
}


2. Non-client area drawing: WM_NCPAINT is the non-client area display update message. All non-client area drawings must be drawn when this message is called back, that is, in the OnNcPaint() function, and use GetWindowDC() to get the handle of the non-client area.

void CClientDrawDlg::OnNcPaint()
{
	// TODO: add message handler code here

	HDC hdc = ::GetWindowDC(m_hWnd);

	RECT rect;

	::GetWindowRect(m_hWnd,&rect);

	::Rectangle(hdc,80,80,rect.right-rect.left-100,rect.bottom-rect.top-100);

	char szstr[200];

	sprintf(szstr,"Non-client area space (%d,%d,%d,%d)",rect.left,rect.top,rect.right,rect.bottom);

	SetTextColor(hdc,RGB(255,0,0));

	TextOut(hdc,0,0,szstr,strlen(szstr));

	::ReleaseDC(m_hWnd,hdc);

	//CDialogEx::OnNcPaint();
}

3. Temporary client area drawing: It can be drawn in response to any message, but when the client area is refreshed, the temporary client area drawing is cleared. Use GetDC() to obtain a temporary client area handle, and use ReleaseDC() to release the handle. The following does a temporary client area drawing in the left mouse click message:

void CClientDrawDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
	HDC hdc = ::GetDC(m_hWnd);

	Ellipse(hdc,point.x-10,point.y-10,point.x+10,point.y+10);

	::ReleaseDC(m_hWnd,hdc);

	CDialogEx::OnLButtonDown(nFlags, point);
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326423531&siteId=291194637