【原创】使用自己的资源-Dialogs in DLL

参考MSDN

By default, MFC uses the resource handle of the main application to load the resource template. 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. You can do this by adding the following code to the beginning of the function:

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));

This swaps the current module state with the state returned from AfxGetStaticModuleState until the end of the current scope.

 

默认情况下,MFC使用主应用程序的资源句柄加载资源模板。如果你的DLL中有一个导出函数,即启动一个DLL中的对话框,此模板实际上是存储在DLL模块。如果要使用它,你需要把它切换为正确的模块状态,你可以在函数的开头添加如下代码

AFX_MANAGE_STATE(AfxGetStaticModuleState( ));

 

Example:

创建一个常规DLL,名为DialogDLL

添加一个Dialog对话框,制作一个简单的加法计算器,界面如图所示

2

制作完成后添加如下一个函数,它的作用是启动自己的一个实例。因为常规DLL导出函数只能是标准C-Style,无法导出MFC

extern __declspec(dllexport) long ShowDialog(long Value1, int Value2)
{
        AFX_MANAGE_STATE(AfxGetStaticModuleState());
        CDialogDLL dlg;
        dlg.m_Value1 = Value1; //specific local Value for CDialogDLL 
        dlg.m_Value2 = Value2;
        dlg.m_Value3 = dlg.m_Value1+dlg.m_Value2;
        dlg.DoModal();
        return dlg.m_Value3;    
}

 

新建一个Win32 Console Application,因为DialogDLL导出的是标准C-Style函数所以它可以被非MFC程序使用

拷贝DialogDLL到工程目录

#include <windows.h>
 
int main()
{
    HINSTANCE hInstance;  //HINSTANCE需要包含windows.h
    typedef long (Fun)(long,long);  //定义函数原型
    Fun* pFun;  //声明函数指针
 
    //返回由LoadLibrary加载的动态链接库的实例句柄
    hInstance=LoadLibrary("DialogDLL");
 
    //找到DLL中ShowDialog函数的地址,函数名调用
    pFun=(Fun*)GetProcAddress(hInstance,"ShowDialog");
    pFun(46,389); //调用函数 
 
    FreeLibrary(hInstance);  //释放调用的DLL资源
 
    return 0;
}
运行效果如图所示
3
posted @ 2009-11-29 00:29  leukotrichia  阅读(933)  评论(0编辑  收藏  举报