Set resource handle in MFC and ATL

When working in MFC/ATL and then using a resource dll can at times cause bugs because resource handle is not properly set. For e.g. if you have a dialog resource in a dll and you instantiate a CDialog which results in an error because resource cannot be located in this application or dll since it’s in the resource dll. So solution for above problem will be to set correct resource handle.

MFC provides two functions…

  1. AfxGetResourceHandle
  2. AfxSetResourceHandle

pretty obvious names. 🙂

So we should first save our current resource handle and then set new resource handle before loading such a resource. Also don’t forget to set our old handle since its good practice.

Sample code snippet.

[sourcecode language=”cpp”]
extern HINSTANCE hResDll = NULL;
HINSTANCE hDefInstance = AfxGetResourceHandle();
AfxSetResourceHandle(hResDll);
CBitmap Bmp;
Bmp.LoadBitmap( IDB_NIBUS_FACE );

AfxSetResourceHandle(hDefInstance);[/sourcecode]

Internally MFC calls FindResource and LoadResource using this handle, so if it’s not properly set this will cause failure in loading resources.

In ATL it’s quite similar except that we’ve got a new function called AddResourceInstance which adds our new resource handle to existing list of handles. So when a look up is done given resource handle is also used. Following functions are provided in ATL to work with resource handles…

  1. AddResourceInstance
  2. GetResourceInstance – Similar to AfxGetResourceHandle
  3. SetResourceInstance – Similar to AfxGetSetResourceHandle

For newbies this is always a painful bug to resolve as they don’t know what went wrong since they expect this to be automagically done.

3 thoughts on “Set resource handle in MFC and ATL

  1. I am having this problem in a .dll with a dialogue box when I call doModal(). When AfxGetResourceHandle() is called my handle is NULL. Using your suggestion, how can I get a good instance handle to begin with? In other words if hDefInstance is null as the result of calling AfxGetResourceHandle(), and hResDll stays NULL, then the debug assertion is thrown. How can I overcome this problem?

    • Hi Softy,

      So where is this dialog resource? If its in the same dll then store the handle that we get in DllMain. This will be your resource handle. So backup old resource handle (a good practice) before calling DoModal and then set this new handle by calling AfxSetResourceHandle. So when DoModal is done restore old resource handle.

      Does this help?

      Sincerely,
      Nibu

Appreciate your comments...