程序:【例7-2】本例调用一幅坦克(或自己的bmp格式文件)的图片,并在用户窗口区上显示
#include <windows.h>
LRESULT WINAPI WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
BOOLEAN InitWindowClass(HINSTANCE hInstance, int nCmdShow);
HWND hWndMain;
int iY = 80;
HBITMAP hBm;
BITMAP bm;
HDC hdcmem;
HDC hDC; //定义设备环境句柄
int iWindowWidth, iWindowHeight;
char cUpWarn[] = " 不能再向上移动了";
char cDownWarn[] = "不能再向下移动了";
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG Message;
hBm = LoadBitmap(hInstance, "pic6_2"); //加载位图
GetObject(hBm, sizeof(BITMAP), (LPVOID)&bm);
//获得位图信息
iWindowWidth = 2 * bm.bmWidth; //得到窗口的宽度
iWindowHeight = 6 * bm.bmHeight; //得到窗口的高度
if (!InitWindowClass(hInstance, nCmdShow))
{
MessageBox(NULL, "创建窗口失败!", "创建窗口", NULL);
return 1;
}
while (GetMessage(&Message, 0, 0, 0))
{
TranslateMessage(&Message);
DispatchMessage(&Message);
}
return Message.wParam;
}
LRESULT WINAPI WndProc(HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps; //定义包含绘图信息的结构体变量
HPEN hPen; //定义画笔句柄
HBRUSH hBrush; //定义画刷句柄
switch (iMessage)
{
case WM_LBUTTONDOWN:
iY = iY - 10; //位图高度-10
InvalidateRect(hWnd, NULL, 1); //刷新用户区
break;
case WM_KEYDOWN:
switch (wParam)
{
case VK_UP: //按上箭头时,位置-10
iY = iY - 10; break;
case VK_DOWN: //按下箭头时,位置+10
iY = iY + 10; break;
}
InvalidateRect(hWnd, NULL, 1); //刷新用户区
break;
case WM_CREATE:
hDC = GetDC(hWnd);
hdcmem = CreateCompatibleDC(hDC);
ReleaseDC(hWnd, hDC);
case WM_PAINT: //处理绘图消息
hDC = BeginPaint(hWnd, &ps); //得到设备环境句柄
if (iY > 0 && iY < iWindowHeight / 2) //当位图完整的在窗口中时
{
SelectObject(hdcmem, hBm); //选入内存句柄
BitBlt(hDC, 60, iY, bm.bmWidth, bm.bmHeight,
hdcmem, 0, 0, SRCCOPY);//输出位图
}
else if (iY <= 0) //当位图的上边界超出了窗口时
TextOut(hDC, 0, 0, cUpWarn, strlen(cUpWarn));//输出警告
else //当位图的下边界超出了窗口时
TextOut(hDC, 0, 0, cDownWarn, strlen(cDownWarn));//输出警告
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
DeleteObject(hBm);
PostQuitMessage(0);
return 0;
default:
return(DefWindowProc(hWnd, iMessage, wParam, lParam));
}
return 0;
}
BOOLEAN InitWindowClass(HINSTANCE hInstance, int nCmdShow)
{
WNDCLASSEX wcex;
HWND hWnd;
TCHAR szWindowClass[] = "窗口示例";
TCHAR szTitle[] = "2019339901078_李海龙_Win32Application_7_2";
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = 0;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
if (!RegisterClassEx(&wcex)) return FALSE;
hWnd = CreateWindow(szWindowClass, szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL
);
if (!hWnd)
return FALSE;
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}