본문으로 바로가기

MFC MDI 화면 배경에 이미지 넣기

category 개발언어/c++ 2016. 11. 16. 04:23

MDIBackgroundImage_demo.zip

1. MDI 화면에 배경 이미지넣기

CWinApp 에서 InitInstance() 에서 Callback 을 실행하는 함수를 추가 해서 WM_ERASEBKGND WM_SIZE 이벤트가 발생 될때 마다 이미지를 그려주는 기능을 구현한다.
먼저 CWinApp 에 콜백 루틴을 구현해서 배경을 그리는 부분을 추가 한다.

HBITMAP hBmp;
// old wnd proc
WNDPROC pfnOldWndProc;
// new one
LRESULT CALLBACK pfnNewWndProc(HWND hwnd, UINT uMsg, WPARAM wParam,LPARAM lParam)
{
	HDC hdc = (HDC)wParam;
	HDC hcompdc;
	RECT rect;

	switch (uMsg)	{
	case WM_SIZE :
		SendMessage(hwnd, WM_ERASEBKGND, (WPARAM)GetDC(hwnd), 0);
		return 1;
	case WM_ERASEBKGND :
		//CallWindowProc(pfnOldWndProc, hwnd, uMsg, wParam, lParam);
		hcompdc = CreateCompatibleDC(hdc);
		SelectObject(hcompdc, hBmp);
		GetClientRect(hwnd, &rect);

		// bitmap dimensions are static for better performance (I assume
		// background image is statically loaded)
		if (0 == StretchBlt(hdc, rect.left, rect.top, rect.right, rect.bottom,
						hcompdc, 0, 0, 1152, 864, SRCCOPY))
					MessageBox(hwnd, "error", "while StretchBlt", MB_OK);

		DeleteDC(hcompdc);
		return 1;
	default :
		return CallWindowProc(pfnOldWndProc, hwnd, uMsg, wParam, lParam);
	}
}

2. 다음은 CWinApp 에서 InitInstance()  에서 콜백 함수를 등록 한다

if (!ProcessShellCommand(cmdInfo))
		return FALSE;

    hBmp = LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP1));
	if (hBmp == NULL)
		MessageBox(NULL, "Error", "Bitmap could not be loaded !!!", MB_OK);

	HWND hMain = pMainFrame->GetWindow(GW_CHILD)->GetSafeHwnd();
	pfnOldWndProc = (WNDPROC)GetWindowLong(hMain, GWL_WNDPROC);
	SetWindowLong(hMain, GWL_WNDPROC, (long)pfnNewWndProc);

	// The main window has been initialized, so show and update it.
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();

 

BitMap을 화면 사이즈에 맞추어 늘려 준다

hcompdc = CreateCompatibleDC(hdc);
SelectObject(hcompdc, hBmp);
GetClientRect(hwnd, &rect);

if (0 == StretchBlt(hdc, 
    rect.left, rect.top, rect.right, rect.bottom,
    hcompdc, 0, 0, 1152, 864, SRCCOPY))
    MessageBox(hwnd, "error",
        "while StretchBlt", MB_OK);

DeleteDC(hcompdc);
return 1;