Tuesday, October 13, 2009

Why AFX_MANAGE_STATE is important in Windows programming?

I happened to write a Windows shell extension about an year back. It was this macro that helped me fix issues when my application was crashing here and there. I am developing an MS Excel extension for a client project and again I ran into the same problem. I spent a couple of days figuring out what was going wrong and finally found that this same old macro was going to fix my issue.

So what is this macro and what does it do?

MFC uses the resource handle of the main application to load the resource templates. If you have an exported function in a DLL, such as one that launches a dialog box in the DLL, this template is actually stored in the DLL module. You need to switch the module state for the correct handle to be used. Otherwise the program crashes as it tries to access some resource resides in a different module. You can do this module switching by adding the following code to the beginning of the function. That is just before using the resource from the other module.

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));

This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope. When the execution flow goes out of the current scope, the module state gets switched back to that of the current application.

No comments: