运行结果:
源代码:
#include <windows.h>
#pragma comment(lib, "winmm.lib") //调用PlaySound函数所需库文件t
#define WINDOW_WIDTH 600
#define WINDOW_HEIGHT 450
#define WINDOW_TITLE L"显示位图"
HINSTANCE hInst;
HDC hdc;
HDC mdc;
HBITMAP hbmp; //需要加载的位图DC
int MyWindowClass(HINSTANCE);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void MyDraw(HDC);
/*****************************************************************************************************************
在不同的应用程序中,在此处添加相关的全局变量
******************************************************************************************************************/
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPreInstace,
LPSTR lpCmdLine, int nCmdShow)
{
MyWindowClass(hInstance);
PlaySound(L"sound.wav", NULL, SND_FILENAME| SND_ASYNC| SND_LOOP); //循环播放背景音乐
if(!InitInstance(hInstance, nCmdShow))
return FALSE;
MSG msg;
while(GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
int MyWindowClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"gamebase";
wcex.hIconSm = NULL;
return RegisterClassEx(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance;
HWND hwnd = CreateWindow(L"gamebase", WINDOW_TITLE, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH, WINDOW_HEIGHT, NULL, NULL, hInstance, NULL);
if(!hwnd)
return FALSE;
MoveWindow(hwnd, 10, 10, WINDOW_WIDTH, WINDOW_HEIGHT, true);
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
hdc = GetDC(hwnd);
//建立与窗口DC兼容的内存DC
mdc = CreateCompatibleDC(hdc);
//从文件中加载位图
hbmp = (HBITMAP)LoadImage(NULL, L"bg.bmp", IMAGE_BITMAP, 600, 450, LR_LOADFROMFILE);
//选用位图对象
SelectObject(mdc, hbmp);
MyDraw(hdc);
ReleaseDC(hwnd, hdc);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
switch(message)
{
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
MyDraw(hdc);
EndPaint(hwnd, &ps);
break;
/**************************************************************************************************************
在退出程序前,往往在此处删除创建的相关资源
***************************************************************************************************************/
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
/***************************************************************************************************************
在函数MyDraw()中进行相关绘制工作
****************************************************************************************************************/
void MyDraw(HDC hdc)
{
//将内存DC的内容映射到窗口DC
BitBlt(hdc, 0, 0, 600, 450, mdc, 0, 0, SRCCOPY);
}