简体   繁体   中英

How to display a MFC dialog from a console application in C++?

I have a simple MFC dialog.

class CMessageBoxWithCustomTextDlg : public CDialogEx
{
// Construction
public:
    CMessageBoxWithCustomTextDlg(CWnd* pParent = NULL); // standard constructor

    __declspec(dllexport) void SetData(std::string& data);

// Dialog Data
    enum { IDD = IDD_MESSAGEBOXWITHCUSTOMTEXT_DIALOG };

    protected:
    virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support


// Implementation
protected:
    HICON m_hIcon;

    // Generated message map functions
    virtual BOOL OnInitDialog();
    afx_msg void OnPaint();
    afx_msg HCURSOR OnQueryDragIcon();
    DECLARE_MESSAGE_MAP()
public:
  afx_msg void OnBnClickedShowMessagebox();
};

I would like to export it as dll and call it from a simple console application. Is it possible?

It is possible; here is how I did it: For your console application have it be simply this:

#include <Windows.h>

typedef void (*EntryFunc)();
int main()
{
   HMODULE hMod = LoadLibrary(L"MFCDll.dll");

   EntryFunc func = (EntryFunc)GetProcAddress(hMod, "entrypoint");
   func();
}

The name of the DLL is MFCDll.dll and there is an exported function called entrypoint in that DLL.

For the DLL I created a New MFC DLL project. And other than the dialog code and the dialog in the resources add this code:

extern "C" __declspec(dllexport) void entrypoint()
{
   AFX_MANAGE_STATE(AfxGetStaticModuleState());
   CMessageBoxWithCustomTextDlg dlg;
   dlg.DoModal();
}

And the console program will load the DLL, call into the DLL and the dialog shows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM