Introduction
This
article
explains how
to use a
child window
(dialog)
exported
from a
dynamically
loaded DLL.
Background
Using the
Visual
Studio 6.0
environment,
I created an
MFC
(SDI)
application
and selected
the
DLL
and exported
the symbols
options.
Using the
code
The
DLL
implementation
Here's the
declaration:
Collapse
Copy
Code
#ifndef __MYDLG_H__
#define __MYDLG_H__
#ifdef MYDLG_API_EXPORTS
#define MYDLG_API __declspec(dllexport)
#else
#define MYDLG_API __declspec(dllimport)
#endif
class CTestDlgDll
{
public:
void CreateMyDialog(HWND hWnd);
void CloseMyDialog();
protected:
CTestDlgDll();
virtual ~CTestDlgDll();
};
extern "C" MYDLG_API void CreateMyDlg(HWND hWnd);
extern "C" MYDLG_API void CloseMyDlg(void);
#endif
and the
implementation:
Collapse
Copy
Code
#include "stdafx.h"
#include "TestDlgDll.h"
#include "TestDlg.h"
CTestDlg *m_pMyDlg;
extern "C" MYDLG_API void CreateMyDlg(HWND hWnd);
extern "C" MYDLG_API void CloseMyDlg(void);
CTestDlgDll* gpThisDLL;
MYDLG_API void CreateMyDlg(HWND hWnd)
{
gpThisDLL->CreateMyDialog(hWnd);
}
MYDLG_API void CloseMyDlg()
{
gpThisDLL->CloseMyDialog();
}
CTestDlgDll::CTestDlgDll()
{
gpThisDLL = this;
m_pMyDlg = NULL;
}
CTestDlgDll::~CTestDlgDll()
{
CloseMyDialog();
}
void CTestDlgDll::CreateMyDialog(HWND hWnd)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if(m_pMyDlg == NULL)
{
CWnd *pParent = CWnd::FromHandle(hWnd);
m_pMyDlg = new CTestDlg(pParent);
m_pMyDlg->Create(IDD_TESTDLG, pParent);
m_pMyDlg->ShowWindow(SW_SHOW);
}
}
void CTestDlgDll::CloseMyDialog()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if(m_pMyDlg != NULL)
{
m_pMyDlg->DestroyWindow();
delete m_pMyDlg;
m_pMyDlg = NULL;
}
}
The EXE(?)
Implementation
Collapse
Copy
Code
typedef void (*PFnCreateMyDialog)(HWND hWnd);
typedef void (*PFnCloseMyDialog)(void);
HMODULE hDLL = NULL;
void CMainFrame::OnMydialogOn()
{
if(hDLL == NULL)
{
CString dllPath = "";
CFileDialog dlg(
TRUE,
NULL,
NULL,
OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST,
_T("dll files|*.dll|"),
AfxGetMainWnd());
if( dlg.DoModal() == IDOK)
{
dllPath = dlg.GetPathName();
hDLL = LoadLibrary(dllPath);
if( hDLL == NULL)
{
AfxMessageBox("LoadLibrary Error !!");
return;
}
PFnCreateMyDialog pFnCreate =
(PFnCreateMyDialog)GetProcAddress(hDLL, "CreateMyDlg");
if( pFnCreate == NULL)
{
FreeLibrary(hDLL);
AfxMessageBox("Get API - Error !!");
return;
}
(pFnCreate)(this->GetSafeHwnd());
}
}
else
{
if(hDLL)
{
PFnCloseMyDialog pFnClose =
(PFnCloseMyDialog)GetProcAddress(hDLL, "CloseMyDlg");
(pFnClose)();
FreeLibrary(hDLL);
hDLL = NULL;
}
}
}