0%

在C++空工程中引入MFC实现的对话框

  1. 创建基本窗体应用
  2. 引入MFC
    1. 初始化
    2. 单个模块
    3. 完整引入的头文件

创建基本窗体应用

  • 打开VS
  • 创建“空项目”
  • 右键工程属性,修改:
    • 高级-MFC的使用:在共享 DLL 中使用 MFC
    • C/C++-预处理器定义:把_CONSOLE替换成_WINDOWS
    • 链接器-系统-子系统:窗口 (/SUBSYSTEM:WINDOWS)
  • Ctrl + Shift + A 添加main.cpp

写入:

1
2
3
4
5
6
7
8
9
10
#include <Windows.h>

int APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nShowCmd)
{
return 0;
}

引入MFC

如果出现fatal error C1189: #error: MFC requires use of Winsock2.h

把afx的#include移到文件最前面就行了

初始化

引入MFC的必要条件!

头文件:

1
#include <afxwin.h>

初始化Afx

1
AfxWinInit(hInstance, hPrevInstance, ::GetCommandLine(), nShowCmd);

单个模块

需要使用哪个模块,直接引入头文件即可

例如,使用文件夹选择对话框:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <afxwin.h>
#include <afxdlgs.h>
#include <Windows.h>

int APIENTRY wWinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nShowCmd)
{
AfxWinInit(hInstance, hPrevInstance, ::GetCommandLine(), nShowCmd);

CFolderPickerDialog dlg;
dlg.DoModal();

return 0;
}

完整引入的头文件

可以写一个头文件mfc.h,引入这个头文件就引入了整个MFC这样(摘抄自VS自建的MFC应用程序)

mfc.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#pragma once

#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // 从 Windows 头中排除极少使用的资料
#endif

#include "targetver.h"

#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 构造函数将是显式的

// 关闭 MFC 的一些常见且经常可放心忽略的隐藏警告消息
#define _AFX_ALL_WARNINGS

#include <afxwin.h> // MFC 核心组件和标准组件
#include <afxext.h> // MFC 扩展

#include <afxdisp.h> // MFC 自动化类

#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h> // MFC 对 Internet Explorer 4 公共控件的支持
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC 对 Windows 公共控件的支持
#endif // _AFX_NO_AFXCMN_SUPPORT

#include <afxcontrolbars.h> // MFC 支持功能区和控制条

#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
#endif

targetver.h

1
2
3
4
5
6
7
8
#pragma once

// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。

//如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并
// 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>