win32 显示 bmp文件
用vs2013 创建一个win32 应用程序,空项目,项目名称是HelloBitmap
拷贝下图的bmp格式文件 abc.bmp 到项目文件所在目录:
添加一个bitmap资源:
进入 资源视图 模式
保存一下:
进入 解决方案资源管理器 模式
在源文件中添加文件:HelloBitmap.cpp
内容如下:
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include "resource.h"
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("HelloWin");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("This program requires Windows NT!"),
szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow(szAppName, // window class name
TEXT("The Hello Program"), // window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT, // initial x size
CW_USEDEFAULT, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL); // creation parameters
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
HDC hdcMem;
PAINTSTRUCT ps;
HINSTANCE hInstance;
BITMAP bitmap;
static HBITMAP hBitmap; // 1 静态变量
static int bmWidth, bmHeight; // 2 静态变量
switch (message)
{
case WM_CREATE:
hInstance = ((LPCREATESTRUCT)lParam)->hInstance; // 3
hBitmap = LoadBitmap(hInstance, MAKEINTRESOURCE(IDB_BITMAP1)); // 4
GetObject(hBitmap, sizeof (BITMAP), &bitmap); // 5
bmWidth = bitmap.bmWidth; // 6
bmHeight = bitmap.bmHeight; // 7
break;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps); // 8
hdcMem = CreateCompatibleDC(hdc); // 9
SelectObject(hdcMem, hBitmap); // 10
BitBlt(hdc, 0, 0, bmWidth, bmHeight, hdcMem, 0, 0, SRCCOPY); // 11 显示位图
DeleteDC(hdcMem); // 12
EndPaint(hwnd, &ps); // 13
break;
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
DeleteObject(hBitmap); // 14
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return 0;
}
编译运行,效果如下:
注意代码中的 带有 // 的语句,尤其是//1 ,//2 和 //14