在WIN32中显示图像,为什么不显示?

Ami*_*mit 4 c++ winapi visual-c++

我想在我在窗口中创建的图片框中加载BitMap图像...使用以下机制创建picBoxDisp ..

picBoxDisp = CreateWindow("STATIC", "image box",
                      WS_VISIBLE |WS_CHILD | SS_BITMAP |WS_TABSTOP | WS_BORDER,
                      50, 50, 250, 300, hwnd , (HMENU)10000, NULL, NULL);
Run Code Online (Sandbox Code Playgroud)

现在接下来我创建了一个hBitmap对象并将图像加载到它...

hBitmap = (HBITMAP) LoadImage(NULL,szFileName,IMAGE_BITMAP,0,0,
                              LR_LOADFROMFILE| LR_DEFAULTSIZE);

SendMessage(picBoxDisp,STM_SETIMAGE,(WPARAM) IMAGE_BITMAP,(LPARAM) NULL);   
//now assign the new image

//Create a compatible DC for the original size bitmap, for example originalMemDc.
HDC originalDC = GetDC((HWND)hBitmap);
HDC originalMemDC = CreateCompatibleDC(originalDC);
if(originalMemDC==NULL){
    MessageBox(NULL,"Problem while creating DC.","Error",MB_OK);
}
//Select hBitmap into originalMemDc.
SelectObject(originalMemDC,hBitmap);

//Create a compatible DC for the resized bitmap, for example resizedMemDc.
HDC picBoxDC = GetDC(picBoxDisp);
HDC resizedMemDC = CreateCompatibleDC(picBoxDC);

//Create a compatible bitmap of the wanted size for the resized bitmap,
HBITMAP hResizedBitmap = CreateCompatibleBitmap(picBoxDC,250,300);

//Select hResizedBitmap into resizedMemDc.
SelectObject(resizedMemDC,hResizedBitmap);

//Stretch-blit from originalMemDc to resizedMemDc.
//BitBlt(resizedMemDC,0,0,250,300,originalMemDC,0,0,SRCCOPY);

BITMAP bmp_old,bmp_new;
GetObject(hBitmap,sizeof(bmp_old),&bmp_old);
GetObject(hResizedBitmap,sizeof(bmp_new),&bmp_new);

StretchBlt ( resizedMemDC,0,0,bmp_new.bmWidth,bmp_new.bmHeight,
            originalMemDC,0,0,bmp_old.bmWidth,bmp_new.bmHeight,
            SRCCOPY);
////De-select the bitmaps.

if((resizedMemDC==NULL)||(hResizedBitmap == NULL)) {
    MessageBox(NULL,"Something is NULL","Error",MB_OK);
}
else
    //Set hResizedBitmap as the label image with STM_SETIMAGE
    SendMessage(picBoxDisp,STM_SETIMAGE, (WPARAM) IMAGE_BITMAP,(LPARAM) hResizedBitmap);
Run Code Online (Sandbox Code Playgroud)

我只是无法理解,为什么上面的代码不起作用?

提前致谢,

Joh*_*ell 5

你误解了STM_SETIMAGE用法.做这个:

hBitmap = (HBITMAP)::LoadImage(NULL, szFileName, IMAGE_BITMAP,
                               0, 0, LR_LOADFROMFILE| LR_DEFAULTSIZE);

if (hBitmap != NULL)
{
    ::SendMessage(picBoxDisp, STM_SETIMAGE,
                  (WPARAM)IMAGE_BITMAP, (LPARAM)hBitmap); 
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果要在将位图设置为标签图像之前调整位图大小,请按照此方案以最简单的方式执行此操作(在调整大小的图像中具有次优质量...):

  1. 例如,为原始大小的位图创建兼容的DC originalMemDc.
  2. 选择hBitmap进入originalMemDc.
  3. 例如,为调整大小的位图创建兼容的DC resizedMemDc.
  4. 例如,为调整大小的位图创建所需大小的兼容位图hResizedBitmap.
  5. 选择hResizedBitmap进入resizedMemDc.
  6. 拉伸从块传送originalMemDcresizedMemDc.
  7. 取消选择位图.
  8. 设置hResizedBitmap为标签图像STM_SETIMAGE

应该管用!