Call MFC dynamic library in Qt program

1. The Qt library calls the MFC module dialog box

  1. The modal dialog box called by QT belongs to the resource class, which needs to be added at the beginning of the export functionAFX_MANAGE_STATE(AfxGetStaticModuleState());
  2. For the Dll transferred from the MFC EXE file, it should be noted that the initialization function in the app class calls the relevant code of the modal dialog box and returns TRUE
  1. Use the wizard to add an MFC dynamic library, such as named MFCLibrary1
  2. Add a dialog resource, and add an MFC interface class such as CTestDialog in the dialog design interface
class CTestDialog : public CDialogEx
{
    
    
	DECLARE_DYNAMIC(CTestDialog)

public:
	CTestDialog(CWnd* pParent = nullptr);   // 标准构造函数
	virtual ~CTestDialog();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum {
    
     IDD = IDD_DIALOG1 };
#endif

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

	DECLARE_MESSAGE_MAP()
public:
	afx_msg void OnBnClickedOk();
};
  1. Add the export class (add the corresponding export macro definition TEST_EX in the engineering project)
//
#pragma once
#ifdef TEST_EX
#define TEST_SDK __declspec(dllexport)
#else
#define TEST_SDK __declspec(dllimport)
#endif
class TEST_SDK TestExport
{
    
    
public:
	void showDialog()
    {
    
    
        //下面这句号一定加,否则QT调用会报(afxwin1.inl 第21行的错误)
        AFX_MANAGE_STATE(AfxGetStaticModuleState());
        //启动模态对话框;
        CTestDialog dlg;
        dialog.DoModal();
    }
};


  1. call in Qt

There is no difference in any way from a normal normal procedure call

QObject::connect(ui.pushButton, &QPushButton::clicked, []()
	{
    
    
		TestExport test;
		test.showDialog();

	});
  1. Achievements

image.png

Two, Qt library embedded MFC dialog control

  1. MFCLibrary1 dynamic library related functions are basically similar
  2. Add a method to get the dialog window handle to the TestExport class
CTestDialog* dialog = new CTestDialog();

void* TestExport::getDialogHandle()
{
    
    
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

    //将对话框当成控件用;
	dialog->Create(IDD_DIALOG1);

	dialog->ShowWindow(SW_SHOW);
	dialog->DoModal();
	return dialog->GetSafeHwnd();
}
  1. The qt program accesses the MFC control
QObject::connect(ui.pushButton, &QPushButton::clicked, [=]()
	{
    
    
		TestExport test;
		void* handle = test.getDialogHandle();

		if(handle)
		{
    
    
			auto m_window = QWindow::fromWinId((WId)handle);


			m_window->setFlags(m_window->flags() | Qt::CustomizeWindowHint | Qt::WindowTitleHint);

			auto mWidget = QWidget::createWindowContainer(m_window);
			this->setCentralWidget(mWidget);
        }
	});
  1. Achievements

image.png

Guess you like

Origin blog.csdn.net/qq_33377547/article/details/125597346