When writing an MFC application, we sometimes want to encapsulate the dialog box in a DLL dynamic library. But when the EXE calls a dialog box in the DLL:
The program first detects the resources in the EXE if there is a corresponding dialog box ID, then the dialog box in the DLL will use the resources in the EXE to create the Build dialog box, which violates our wishes.
1 The following situation can be correctly invoked DLL Project dialog box:
In EXE project resource, the dialog box ID is
#define IDD_EXE_DIALOG 5000
In DLL Engineering, the dialog box ID is
#define Idd_dll_dialog 5001
2 The following situation can be incorrectly called EXE Project dialog box:
In EXE project resource, the dialog box ID is
#define IDD_EXE_DIALOG 5000
In DLL Engineering, the dialog box ID is
#define IDD_DLL_DIALOG 5000
Dialog ID is automatically generated by Visual Studio, manual modification ID, to reach the resource does not conflict, for small projects can endure. But it's also a hassle for thousands of of dialogs, even tens of thousands of dialog boxes. MFC provides the following two functions, so we simply switch the resource handle before creating the dialog box.
Get the current resource module handle
HINSTANCE Afxapi AfxGetResourceHandle ();
Set the current resource module handle
void Afxapi AfxSetResourceHandle (hinstance hinstresource);
Then overload the DoModal () function on the dialog box that needs to be exported in the DLL project
INT_PTR Cdlldialog::D omodal ()
{
//get old handle
hinstance old_hinstance = AfxGetResourceHandle ();
Gets the dynamic library instance
hinstance dll_hinstance = GetModuleHandle (_t ("DialogDll.dll"));
Set resource module handle to Dynamic library resource handle
afxsetresourcehandle (dll_hinstance);
Call CDialog::D omodal () function
int_ptr PTR = CDialog::D omodal ();
Restore resource handle
afxsetresourcehandle (old_hinstance);
return ptr;
}
To add a menu response event to an EXE application:
Ctestdialogdoc command
#include "DllDialog.h"
#include "ExeDialog.h"
void Ctestdialogdoc::ontest ()
{
//TODO: Add Command handler code here
cdlldialog Dlldlg;
Dlldlg. DoModal ();
Cexedialog Exedlg;
Exedlg. DoModal ();
}