1. 程式人生 > 實用技巧 >MFC DLL 的建立和呼叫

MFC DLL 的建立和呼叫

1.

新建DLL工程

MFC DLL --> 建立規則 DLL --> 帶靜態連結 MFC 的規則 DLL

編譯生成 .lib .dll 檔案

完整.h檔案程式碼

 1 // testMfcDll.h : testMfcDll DLL 的主標頭檔案
 2 //
 3 
 4 #pragma once
 5 
 6 #ifndef __AFXWIN_H__
 7     #error "在包含此檔案之前包含“stdafx.h”以生成 PCH 檔案"
 8 #endif
 9 
10 #include "resource.h"        // 主符號
11 
12 
13 // CtestMfcDllApp
14 // 有關此類實現的資訊,請參閱 testMfcDll.cpp 15 // 16 17 class CtestMfcDllApp : public CWinApp 18 { 19 public: 20 CtestMfcDllApp(); 21 22 // 重寫 23 public: 24 virtual BOOL InitInstance(); 25 26 DECLARE_MESSAGE_MAP() 27 }; 28 29 class __declspec(dllexport) testMfcDll; 30 class testMfcDll 31 { 32 public:
33 testMfcDll(){}; 34 virtual ~testMfcDll(){}; 35 void sayHello(); 36 CString &sayHelloWord(); 37 void sayWhat(CString &); 38 39 CString strHello; 40 };

完成.cpp 檔案程式碼

 1 // testMfcDll2.cpp : 定義 DLL 的初始化例程。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "testMfcDll2.h"
6 7 #ifdef _DEBUG 8 #define new DEBUG_NEW 9 #endif 10 11 // 12 //TODO: 如果此 DLL 相對於 MFC DLL 是動態連結的, 13 // 則從此 DLL 匯出的任何調入 14 // MFC 的函式必須將 AFX_MANAGE_STATE 巨集新增到 15 // 該函式的最前面。 16 // 17 // 例如: 18 // 19 // extern "C" BOOL PASCAL EXPORT ExportedFunction() 20 // { 21 // AFX_MANAGE_STATE(AfxGetStaticModuleState()); 22 // // 此處為普通函式體 23 // } 24 // 25 // 此巨集先於任何 MFC 呼叫 26 // 出現在每個函式中十分重要。這意味著 27 // 它必須作為函式中的第一個語句 28 // 出現,甚至先於所有物件變數宣告, 29 // 這是因為它們的建構函式可能生成 MFC 30 // DLL 呼叫。 31 // 32 // 有關其他詳細資訊, 33 // 請參閱 MFC 技術說明 33 和 58。 34 // 35 36 // CtestMfcDll2App 37 38 BEGIN_MESSAGE_MAP(CtestMfcDllApp, CWinApp) 39 END_MESSAGE_MAP() 40 41 42 // CtestMfcDll2App 構造 43 44 CtestMfcDllApp::CtestMfcDllApp() 45 { 46 // TODO: 在此處新增構造程式碼, 47 // 將所有重要的初始化放置在 InitInstance 中 48 } 49 50 51 // 唯一的一個 CtestMfcDll2App 物件 52 53 CtestMfcDllApp theApp; 54 55 56 // CtestMfcDll2App 初始化 57 58 BOOL CtestMfcDllApp::InitInstance() 59 { 60 CWinApp::InitInstance(); 61 62 return TRUE; 63 } 64 65 66 void testMfcDll::sayHello() 67 { 68 //這是win的MessageBox 69 MessageBox(NULL, _T("hello"), _T("提示"), MB_OK); 70 } 71 72 73 CString& testMfcDll::sayHelloWord() 74 { 75 strHello = _T("hello world"); 76 return strHello; 77 } 78 79 80 void testMfcDll::sayWhat(CString &str) 81 { 82 if(str == _T("hello")) 83 { 84 str = _T("get way"); 85 MessageBox(NULL, _T("get way"), _T("提示"), MB_OK); 86 }else 87 { 88 MessageBox(NULL, _T("hello"), _T("提示"), MB_OK); 89 } 90 }

2.

新建 MFC 對話方塊程式呼叫 DLL

MFC 應用程式 --> 基於對話方塊 在靜態中使用 MFC -->其他選項都是預設

把 DLL 的 .h 檔案加入到專案,把編譯生成的 .lib 檔案加入到專案資源

在對話方塊程式中增加一個按鈕,在按鈕的點選訊息實現函式中增加程式碼

1 testMfcDll test;
2 test.sayHello();// hello
3 CString str = _T("hello");
4 str = test.sayHelloWord();
5 test.sayWhat(str);// hello
6 MessageBox(str);// hello world