函数功能:该函数可以创建一个具有特定宽度、高度和颜色格式的位图。
函数原型:HBITMAP CreateBitmaplndirect(CONST BITMAP *lpbm);
参数:
ipbm:指向BITMAP结构的指针。该结构包含有关位图的信息。如果应用程序将其成员bmWidth或bmHeight设为0,那么CreateBitmaplndirect将返加一个只有1个像素点的单色位图的句柄。
函数原型:HBITMAP CreateBitmaplndirect(CONST BITMAP *lpbm);
参数:
ipbm:指向BITMAP结构的指针。该结构包含有关位图的信息。如果应用程序将其成员bmWidth或bmHeight设为0,那么CreateBitmaplndirect将返加一个只有1个像素点的单色位图的句柄。
- #include <windows.h>
- #pragma comment(lib,"Msimg32.lib")
- HINSTANCE g_hIns;
- HWND g_hWnd;
- LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
- int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow)
- {
- g_hIns=hInstance;
- 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("error"),szAppName,MB_ICONERROR|MB_OK);
- return 0;
- }
- hWnd=CreateWindow(szAppName,TEXT("The hello program"),WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL);
- ShowWindow(hWnd,iCmdShow);
- UpdateWindow(hWnd);
- while(GetMessage(&msg,hWnd,0,0))
- {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- return msg.wParam;
- }
- LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
- {
- static HDC hdc;
- static HDC hBitmapDC,hBitmapDC1;
- static HBITMAP hBitmap,hBitmap1;
- static BITMAP bm;
- static BYTE *p;
- int index = 0;
- PAINTSTRUCT ps;
- switch (message)
- {
- case WM_PAINT :
- hdc=BeginPaint(hWnd,&ps);
- hBitmapDC1 = CreateCompatibleDC(hdc);
- hBitmap1 = CreateCompatibleBitmap(hdc,100,100);
- SelectObject(hBitmapDC1,hBitmap1);
- TextOut(hBitmapDC1,0,0,TEXT("asdf"),4);
- GetObject(hBitmap1,sizeof(BITMAP),&bm);
- p = new BYTE[bm.bmHeight * bm.bmWidth * bm.bmBitsPixel];
- if (p == NULL)
- {
- return E_FAIL;
- }
- COLORREF col;
- for(int i = 0;i<bm.bmHeight*bm.bmWidth;i++)
- {
- col = GetPixel(hBitmapDC1,(i+1)%bm.bmWidth,(i+1)/bm.bmWidth);
- p[index++] = (BYTE)GetRValue(col);
- p[index++] = (BYTE)GetGValue(col);
- p[index++] = (BYTE)GetBValue(col);
- p[index++] = 255;
- }
- bm.bmBits = p;//注意GetObject只是取得结构信息,并没有取得数据,所以数据要手动添加
- hBitmap = CreateBitmapIndirect(&bm);
- hBitmapDC = CreateCompatibleDC(hdc);
- SelectObject(hBitmapDC,hBitmap);
- BitBlt(hdc,0,0,100,100,hBitmapDC,0,0,SRCCOPY);
- DeleteObject(hBitmap);
- DeleteObject(hBitmap1);
- DeleteObject(hBitmapDC);
- DeleteObject(hBitmapDC1);
- EndPaint (hWnd, &ps) ;
- break;
- case WM_DESTROY :
- PostQuitMessage (0) ;
- break ;
- default:
- return DefWindowProc (hWnd, message, wParam, lParam) ;
- }
- return 1;
- }