Gonghen Zhang
Gonghen Zhang

Reputation: 1

When I run the mfc program alone, I encountered a problem,Expression:m_hBitmap!=0

enter image description here

CString strBmpPath = _T(".\\res\\bgimg.png");
CImage img;
img.Load(strBmpPath);
MoveWindow(0, 0, img.GetWidth(), img.GetHeight());
CBitmap bmpTmp;
bmpTmp.Attach(img.Detach());
m_bkBrush.CreatePatternBrush(&bmpTmp);
CDialogEx::OnInitDialog();

Upvotes: 0

Views: 450

Answers (1)

IInspectable
IInspectable

Reputation: 51503

This is a combination of two bugs:

  1. Using a relative path (which is always wrong) to reference a file system object, and
  2. Failure to check for errors (which, again, is always wrong)

In detail, what's happening is that img.Load(strBmpPath) fails to load the image specified as a relative path. This, presumably, succeeds when run under the debugger, since the IDE helpfully adjusts the current working directory so that the relative path resolves to a file system object.

This generally won't happen when you launch the application outside the IDE. The current working directory then is no longer under your control, and the image file isn't where your code is looking for it.

With img not holding a valid image, the call to img.Detach() fails the debug assertion, probably something like ATLASSUME( m_hBitmap != NULL ).

The immediate fix would be to check for errors when Load()-ing the image. Another option would be to construct a fully qualified path to the image resource.

Though, what you probably intended to do was to compile ".\res\bgimg.png" as a binary resource into the executable image, and load it using CImage::LoadFromResource instead.

Upvotes: 1

Related Questions