Win32 Unable to add custom toolbar icon having transparency - c++

I am using this code to add a toolbar to the window with one button having a custom image:
HWND hToolbar = CreateWindow(TOOLBARCLASSNAME, NULL,WS_CHILD |
TBSTYLE_FLAT|TBSTYLE_AUTOSIZE |TBSTYLE_LIST|CCS_BOTTOM, 0, 0, 0, 0,
hwnd, NULL, ghInstance, NULL); //create the toolbar
SendMessage(hToolbar, WM_SETFONT, (WPARAM)hFontBold,
static_cast<LPARAM>(MAKELONG(TRUE, 0))); //set the font. there cannot be the problem
//↓↓↓↓↓**ILC_COLOR32 is specificied here but 32bit bmp is still not showing**//
auto hImagelist = ImageList_Create(32, 32,ILC_COLOR32|ILC_MASK,1, 0);
//↑↑↑↑↑**ILC_COLOR32 is specificied here but 32bit bmp is still not showing**//
HBITMAP bitmap = static_cast<HBITMAP>(ghInstance,
MAKEINTRESOURCE(ID_IMG_SPAWN),// <- ID_IMG_SPAWN is my custom resource
IMAGE_BITMAP, 32, 32, NULL));
ImageList_Add(hImagelist, bitmap, nullptr);
SendMessage(hToolbar, TB_SETIMAGELIST,static_cast<WPARAM>(0),(LPARAM)hImagelist);
In the code above, ID_IMG_SPAWN is the resource bmp image I imported to Visual Studio. However, Visual Studio threw an error saying it didn't recognize my bmp, and the bmp showed up blank when running the application.
Visual Studio told me my bmp wasn't recognized, see the below error:
When the app runs it looks as below:
I learned that Visual Studio hereby recognizes ONLY 24bit bmp.
So, I converted the bmp to 24bit and imported it again, changed ILC_COLOR32 to ILC_COLOR24, that really worked. No error and my image were shown on the button.
However, I lost my alpha channel. Because 24bit bitmap does not support an alpha channel, my image ended up having an ugly square background.

Try something like this (Note I used a "BINARY" resource.. maybe it will work with others too but not sure.. This code works with 32-bit bitmaps, alpha-transparent PNGs, and JPEG):
#include <windows.h>
#include <gdiplus.h>
HBITMAP LoadBitmapFromResource(DWORD ResourceID, bool transparent = true)
{
HANDLE hGlobal = NULL;
ULONG_PTR GDIToken = 0;
Gdiplus::Image* Img = NULL;
Gdiplus::GdiplusStartupInput GDIStartInput = NULL;
Gdiplus::GdiplusStartup(&GDIToken, &GDIStartInput, NULL);
HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(ResourceID), "BINARY");
if (!hResource) {return NULL;}
HGLOBAL hFileResource = LoadResource(NULL, hResource);
if (!hFileResource) {return NULL;}
LPVOID lpFile = LockResource(hFileResource);
if (!lpFile) {return NULL;}
DWORD dwSize = SizeofResource(NULL, hResource);
if (!dwSize) {return NULL;}
void* data = LockResource(hFileResource);
if (!data) {return NULL;}
IStream* pStream = NULL;
hGlobal = GlobalAlloc(GMEM_FIXED, dwSize);
memcpy(hGlobal, data, dwSize);
UnlockResource(hFileResource);
FreeResource(hFileResource);
if (CreateStreamOnHGlobal(hGlobal, true, &pStream) == S_OK)
{
Img = new Gdiplus::Image(pStream, false);
pStream->Release();
GlobalFree(hGlobal);
hGlobal = NULL;
HBITMAP hBitmap = NULL;
static_cast<Gdiplus::Bitmap*>(Img)->GetHBITMAP(transparent ? Gdiplus::Color::Transparent : Gdiplus::Color(0, 0, 0), &hBitmap);
delete Img;
Gdiplus::GdiplusShutdown(GdiImage::GDIToken);
GDIStartInput = NULL;
GDIToken = 0;
return hBitmap;
}
GlobalFree(hGlobal);
hGlobal = NULL;
Gdiplus::GdiplusShutdown(GdiImage::GDIToken);
GDIStartInput = NULL;
GDIToken = 0;
return NULL;
}
You will have to link against GDIPlus. It's not very nice to constantly startup and shutdown GDIPlus for every image you load.. so it's best to move that somewhere.. but other than that, everything should work just fine.
There are other ways without GDIPlus but it makes for a long post..

I learned that Visual Studio hereby recognizes ONLY 24bit bmp.
No, that's wrong. Visual Studio supports alpha-premultiplied 32-bit bitmaps.
32-bit bitmap has 8 bits for ALPHA, it's capable to make a smooth effect.
To show a 32-bit bitmap properly, you have to:
specify ILC_COLOR32
change the resource of ID_IMG_SPAWN to a 32-bit bitmap with premultiplied alpha.
create a DIB section to your bitmap when loading
(Win32's format requirement is very strict)
Q: How to create a DIB section to the bitmap?
A: Specify LR_CREATEDIBSECTION in the last parameter of LoadImage.
Explanation:
LoadImage((HINSTANCE)GetWindowLong(hwnd,GWL_HINSTANCE),MAKEINTRESOURCE(ID_IMG_SPAWN), IMAGE_BITMAP,32, 32,NULL)
This is your code of the LoadImage function. See the MSDN document of LoadImage, to create the DIB section, all you need is to specify LR_CREATEDIBSECTION in the last parameter of LoadImage.
Q: How to get a BMP with premultiplied alpha?
A: Pixelformer can help you convert your alpha-channeled file to a premultiplied-alpha BMP.
The steps are
Open your image (any format) in Pixelformer and choose Export from the menu
Select A8:R8:G8: B8 (32bpp) and Premultiplied Alpha, then click Ok.
Then you can save your BMP file! Import this BMP file to Visual Studio resources, replacing your previous 24-bit BMP.
Then, you don't need to use the ImageList_AddMasked (which makes the image sharp) anymore, because you already have a recognizable ALPHA in your 32-bit BMP. So, straight use ImageList_Add.
Okay, after the manipulations explained above your code should be this:
// Create the toolbar
HWND hToolbar = CreateWindow(TOOLBARCLASSNAME,NULL,
WS_CHILD | TBSTYLE_FLAT | TBSTYLE_AUTOSIZE | TBSTYLE_LIST | CCS_BOTTOM,
0, 0, 0, 0, hwnd, NULL, ghInstance, NULL);
// Set the font (this cannot be the problem)
SendMessage(hToolbar, WM_SETFONT, (WPARAM)hFontBold,
static_cast<LPARAM>(MAKELONG(TRUE, 0)));
auto hImagelist =
ImageList_Create(32, 32,ILC_COLOR32 /*DON'T NEED THE MASK. CHANGED TO ILC_COLOR32.*/, 1, 0);
HBITMAP bitmap = static_cast<HBITMAP>(LoadImage((HINSTANCE)GetWindowLong(hwnd,
GWL_HINSTANCE), MAKEINTRESOURCE(ID_IMG_SPAWN), IMAGE_BITMAP,
32, 32, LR_CREATEDIBSECTION /*THIS IS IMPORTANT*/ ));
ImageList_Add(hImagelist, bitmap, NULL);
SendMessage(hToolbar, TB_SETIMAGELIST, static_cast<WPARAM>(0), (LPARAM)hImagelist);
This worked fine as below.
These I answered above is well enough to solve this problem. You may wonder "What means DIB bitmaps?" "What is Premultiplied Alpha?". Those are the deep topics.
To learn DIB bitmaps and Premultiplied Alpha, see the links.

If you are using Visual Studio 2010 or higher (i guess), you can use PNG files. As stated here.

Related

glfwSetWindowIcon from an embedded resource with transparency

I'm trying to achieve what almost every application does, and that's to have an embedded icon which I can show in the title bar and taskbar.
The requirements are:
The icon must support transparency
The icon must be embedded, not a separate file on the disk
The icon file format doesn't matter; can be ico, bmp or anything else that works.
I tried to create a bmp in paint.net, but LoadImage kept returning NULL. I recreated it as a 32-bit png, then used
this tool to convert it to a 32-bit bmp, my reasoning for which being to get LoadImage working again, and this time with transparency. I'm using LoadImage because apparently LoadBitmap isn't so well-supported.
resources.rc:
100 BITMAP "icons\\icon.bmp"
code:
HBITMAP h_bmp = (HBITMAP)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(100), IMAGE_BITMAP, 0, 0, 0);
HDC dc = CreateCompatibleDC(NULL);
HBITMAP bmp_old = (HBITMAP)SelectObject(dc, h_bmp);
BITMAP bmp = {};
GetObject(h_bmp, sizeof(bmp), &bmp);
BITMAPINFO info;
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
info.bmiHeader.biWidth = bmp.bmWidth;
info.bmiHeader.biHeight = -bmp.bmHeight;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = bmp.bmBitsPixel;
info.bmiHeader.biCompression = BI_RGB;
info.bmiHeader.biSizeImage = ((bmp.bmWidth * bmp.bmBitsPixel + 31) / 32) * 4 * bmp.bmHeight;
std::vector<unsigned char> pixels;
pixels.resize(info.bmiHeader.biSizeImage);
GetDIBits(dc, h_bmp, 0, bmp.bmHeight, &pixels[0], &info, DIB_RGB_COLORS);
SelectObject(dc, bmp_old);
DeleteDC(dc);
GLFWimage image = { bmp.bmWidth, bmp.bmHeight, &pixels[0] };
glfwSetWindowIcon(window, 1, &image);
There were two issues with the image; firstly it was displaying upside-down, hence the negation of the height above. Secondly, the RGB channels are flipped and I have no idea how to fix it.
So, is there a simpler way to do this, perhaps without having to suffer bmp formats and needing 3rd-party tools, and if not, how can I get the colours displaying properly?
Windows (HWNDs) uses HICONs. A HICON is a handle to an icon loaded from a .ico file or an icon resource. A .ico file consists of one or more bmp and/or png files in various sizes. You should use a real icon editor to create your icon. You can find several free editors if you look around.
Once you have the ico file in your resources, load it with LoadImage(hInst, ..., IMAGE_ICON, ..., LR_SHARED) and apply it with SetClassLongPtr or WM_SETICON.
Solved as per #user253751's comment;
SetClassLongPtr(glfwGetWin32Window(window), GCLP_HICON, (LONG_PTR)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(100)));
Much simpler than I expected!

Windows 10 CredentialProvider Tile Image transparency

A while ago, I have created a CredentialProvider for Windows 7 that showed a custom tile image for the user. When I tested my CredentialProvider on Windows 10, I noticed that the tile image is not round as the usual Windows user image is, so I assumed, I have to provide my own round image with transparency. I tried to load a transparent PNG with the round shape and pass the corresponding HBITMAP in the ICredentialProviderCredentiall::GetBitmapValue() function. Unfortunately, instead of being transparent, the background of the PNG is white. Is there any way to show the actual transparency? Since the HBITMAP is drawn by LogonUI itself, I cannot modify the drawing behavior.
To create the HBITMAP out of my PNG resource, I use the following function:
HBITMAP LoadPNG(HINSTANCE hInst, int resourceId)
{
HGLOBAL hGlobal;
LPSTREAM pStream;
HBITMAP tBmp = NULL;
ULONG_PTR token = 0;
Gdiplus::GdiplusStartupInput input = NULL;
Gdiplus::GdiplusStartup(&token, &input, NULL);
if (token != 0)
{
HRSRC hRsrc = FindResource(hInst, MAKEINTRESOURCE(resourceId), TEXT("PNG"));
HGLOBAL hGlob1 = LoadResource(hInst, hRsrc);
int size = SizeofResource(hInst, hRsrc);
hGlobal = GlobalAlloc(GMEM_FIXED, size);
LPVOID resPtr = LockResource(hGlob1);
memcpy(hGlobal, resPtr, size);
FreeResource(hGlob1);
CreateStreamOnHGlobal(hGlobal, true, &pStream);
Gdiplus::Bitmap* bmp = new Gdiplus::Bitmap(pStream, false);
bmp->GetHBITMAP(Gdiplus::Color::Transparent, &tBmp);
Gdiplus::GdiplusShutdown(token);
}
return tBmp;
}
I tried also other values for the GetHBITMAP() background color parameter such as AlphaMask and AlphaShift, but these did not work either (instead, the white background turned black)
Is there any way to accomplish my goal?
The newest Credential Provider Technical Reference (which is not that easy to find on MSDN) actually tells what the issue with the tile image is:
In Windows 10, the selected User/V1/PLAP credential provider has an
image size of 192x192. The ones on the bottom left list is of 48x48.
Note LogonUI uses circular image for user and square image for V1/PLAP
according to the new design direction. The image size of V2 Credential
Provider tile under a selected user is 48x48.
If I read the documentation correctly then the challenge must be somehow to convince the LogonUI that its a User and not a V1/PLAP, I think this could be archieved returning a dummy user in the GetSerialization call.

Windows 7 and ScreenShot.cpp GDI+ PNG problemo

was using XP without issue for a long time. switched to 7 and trying to capture screenshots with my previously functioning code no longer works. simple concept and relatively generic code...just find the window that i call and save it as a .png. any ideas what might make this bad boy run again? can't debug with my current setup, but it makes it all the way and spits out the error message after bmp->save(...) ...couldn't save image file. edit: also a file does get created/saved, but it is blank and not written to. perhaps the bitmap encoding or GDI is screwed up?
bool CScreenShot::Snap(CString wintitle, CString file, CString& ermsg)
{
ermsg = ""; // no error message
// create screen shot bitmap
EnumWinProcStruct prm = {0, (LPSTR)(LPCTSTR)wintitle, 0};
// Find the descriptor of the window with the caption wintitle
EnumDesktopWindows(0, EnumWindowsProc, (LPARAM)&prm);
if(!prm.hwnd)
{
ermsg.Format("couldn't find window \"%s\"", wintitle);
return false;
}
// Make the window the topmost window
SetWindowPos(prm.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
Sleep(300);
// Get device context for the top-level window and client rect
HDC hDC = GetDC(prm.hwnd);
RECT rc;
GetClientRect(prm.hwnd, &rc);
HDC memDC = CreateCompatibleDC(hDC);
// Set the size and color depth for the screen shot image
BITMAPINFO bmpInfo;
memset(&bmpInfo, 0, sizeof(bmpInfo));
bmpInfo.bmiHeader.biSize = sizeof(bmpInfo.bmiHeader);
bmpInfo.bmiHeader.biWidth = rc.right - rc.left;
bmpInfo.bmiHeader.biHeight = rc.bottom - rc.top;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biBitCount = 24;
bmpInfo.bmiHeader.biCompression = BI_RGB;
bmpInfo.bmiHeader.biSizeImage = bmpInfo.bmiHeader.biWidth * bmpInfo.bmiHeader.biHeight * 3;
// Create memory buffer and perform a bit-block transfer of the color data from the window to the memory
LPVOID addr;
HBITMAP memBM = CreateDIBSection(memDC, &bmpInfo, DIB_RGB_COLORS, &addr, 0, 0);
HGDIOBJ stdBM = SelectObject(memDC, memBM);
BOOL OK = BitBlt(memDC, 0, 0, bmpInfo.bmiHeader.biWidth, bmpInfo.bmiHeader.biHeight, hDC, 0, 0, SRCCOPY);
ReleaseDC(prm.hwnd, hDC);
SetWindowPos(prm.hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
if(GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL) != Ok)
{
ermsg.Format("couldn't start GDI+");
return false;
}
// Create a Bitmap object for work with images defined by pixel data from the GDI HBitmap and the GDI HPalette.
Bitmap* bmp = ::new Bitmap(memBM, DIB_RGB_COLORS);
SelectObject(memDC, stdBM);
DeleteObject(memBM);
DeleteDC(memDC);
// Find the encoder for "image/png" mime type
CLSID encoderClsid;
EncoderParameters encoderParameters;
GetEncoderClsid(L"image/png", &encoderClsid);
encoderParameters.Count = 0;
// Convert file name to Unicode (wide-char) string.
WCHAR fn[_MAX_PATH];
MultiByteToWideChar(CP_THREAD_ACP, MB_PRECOMPOSED, file, file.GetLength() + 1, fn, _MAX_PATH);
// Save the screen shot into the specified file using image encoder with the mime style "image/png"
if(bmp->Save(fn, &encoderClsid, &encoderParameters) != Ok)
{
ermsg.Format("couldn't save image file \"%s\"", file);
return false;
}
::delete bmp;
GdiplusShutdown(gdiplusToken);
return true;
}
The error message implies that you're trying to save the file to a folder that you don't have permission to write to. Many folders such as Program Files are now protected. Since you didn't include the path in your sample code I'm unable to determine if this is the actual problem.
Edit: Another possibility is that the Bitmap is improperly constructed which causes the Save to fail. The second parameter to the constructor is supposed to be a handle to a palette, I think DIB_RGB_COLORS would be invalid here and you should use NULL. Also there are a couple of caveats noted in the Microsoft documentation and perhaps the different OS versions react differently when you break the rules:
You are responsible for deleting the GDI bitmap and the GDI palette. However, you should not delete the GDI bitmap or the GDI palette until after the GDI+ Bitmap::Bitmap object is deleted or goes out of scope.
Do not pass to the GDI+ Bitmap::Bitmap constructor a GDI bitmap or a GDI palette that is currently (or was previously) selected into a device context.
win7 won't accept encoderParameters.Count == 0 for some reason. Set that == 1 and you should be all set.
you probably could also just remove that parameter from Save() (overloaded)

Displaying image in WIN32, Why its not displayed?

I want to load a BitMap image in a pic box I created inside a window...picBoxDisp is created using following mechanism..
picBoxDisp = CreateWindow("STATIC", "image box",
WS_VISIBLE |WS_CHILD | SS_BITMAP |WS_TABSTOP | WS_BORDER,
50, 50, 250, 300, hwnd , (HMENU)10000, NULL, NULL);
Now Next I created a hBitmap object and loaded an image in to it...
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);
I just cant understand, why the above code is not working ?
Thanks in advance,
You misunderstood the STM_SETIMAGE usage. Do this:
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);
}
EDIT: If you want to resize the bitmap before setting it as the label image, then follow this scheme for the simplest possible way to do it (with sub-optimal quality in the resized image...):
Create a compatible DC for the original size bitmap, for example originalMemDc.
Select hBitmap into originalMemDc.
Create a compatible DC for the resized bitmap, for example resizedMemDc.
Create a compatible bitmap of the wanted size for the resized bitmap, for example hResizedBitmap.
Select hResizedBitmap into resizedMemDc.
Stretch-blit from originalMemDc to resizedMemDc.
De-select the bitmaps.
Set hResizedBitmap as the label image with STM_SETIMAGE
Should work!
The static control won't stretch the image to its size. You could use SS_CENTERIMAGE but it either clips or fills the empty space with the color of the top left pixel (see http://msdn.microsoft.com/en-US/library/b7w5x74z.aspx). You'd have to stretch the bitmap yourself before sending it to the static control.
You're trying to assign an image to a static control, so you don't need to draw the image but to set the image on it.
// set the image
HBITMAP hold = (HBITMAP)SendMessage(hpicBoxDc, STM_SETIMAGE, IMAGE_BITMAP, LPARAM(hBitmap));
// clear the old image
if(hold && hold != hBitmap)
DeleteObject(hold );

Load a CBitmap dynamically

I have a Bitmap image that i want to load dynamically. But I am unable to load it.
CBitmap bmp;
bmp.LoadBitmap("c:\\aeimg");
it does not seem to be working.
Can someone please help me.
Thanks.
You can also try something like this:
CImage image;
image.Load(_T("C:\\image.png"));
CBitmap bitmap;
bitmap.Attach(image.Detach());
According to CBitmap documentation: LoadBitmap() function takes resource identifier of the bitmap or resource id of the bitmap.
You can't specify the path of the bitmap file.
E.g.
MyProject.rc
------------
MYBMP BITMAP "res\myimage.bmp"
and make sure that resource.h does not have any entry of MYBMP otherwise during preprocessing its replaced by id and ultimately LoadBitmap() will fail since application can't locate the resource as FindResource() fails.
Now do this :
CBitmap bmp;
bmp.LoadBitmap(L"MYBMP");
It will definitely load the bitmap.
To load a bitmap from a file, you want to use LoadImage with the LR_LOADFROMFILE flag.
CBitmap doesn't support directly reading from a .bmp file. You can instead make use of CImage class as suggested in other answers. You'll need to include atlimage.h in your code to make CImage work:
#include <atlimage.h>
:
CImage img;
img.Load (_T("C:\\image.bmp"));
CBitmap bitmap;
bitmap.Attach(img.Detach());
Another way is to load the image using LoadImage Win32 API and then attaching CBitmap to that:
HBITMAP hBitmap = (HBITMAP)LoadImage(NULL,"c:\\image.bmp",
IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (hBitmap != NULL)
bitmap.Attach(hBitmap);
CImage doesn't work with png last time I tried / checked. Have a look at CxImage - http://www.codeproject.com/KB/graphics/cximage.aspx .
It could be as simple as you forgetting to escape the backslash.
Instead of
bmp.LoadBitmap("c:\aeimg");
use
bmp.LoadBitmap("c:\\aeimg");
Otherwise you're passing an invalid path to the LoadBitmap method.
CString filename;
TCHAR szFilter[] = _T("Bitmap (*.bmp)|*.bmp|PNG (*.png)|*.png||");
CFileDialog selDlg(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT | OFN_EXTENSIONDIFFERENT, szFilter, this);
if (selDlg.DoModal() == IDOK)
{
filename = selDlg.GetPathName();
CImage image;
HBITMAP hBitmap = (HBITMAP)LoadImage(NULL,filename, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (hBitmap)
{
// Delete the current bitmap
if (m_bmpBitmap.DeleteObject())
m_bmpBitmap.Detach(); // If there was a bitmap, detach it
// Attach the currently loaded bitmap to the bitmap object
m_bmpBitmap.Attach(hBitmap);
Invalidate();
}
}
When using the solutions mentioned to date, with a member variable of CBitmap I kept getting memory leaking every time I loaded the CImage onto the CBitmap. I solved this with the following code:
CString _fileName(/*Path to image*/);
CImage _image;
HRESULT hr = _image.Load(_fileName);
if (SUCCEEDED(hr)) {
if (m_Display.m_bmpImage.DeleteObject())
m_Display.m_bmpImage.Detach();
m_bmpImage.Attach(_image->Detach());
}