02. 自建工程使用MFC框架的步骤
一.自建工程使用MFC框架的步骤
1. 新建空项目,更改选项


2.需要自己写两个类
class CMyApp : public CWinApp {
};
class CMyDlg :public CDialogEx {
};
这两个类要包afxwin.h和afxdialogex.h两个含头文件,编译时有警告,所以再包含sdkddkver.h。把这3个头文件写在framework.h中,方便使用。
#pragma once #include <sdkddkver.h> #include <afxwin.h> #include <afxdialogex.h>
3.CMyApp.cpp中定义全局变量g_myApp
#include "CMyApp.h" #include "CMyDlg.h" CMyApp g_myApp;
4.CMyApp.h中声明全局变量g_myApp
#pragma once
#include "framework.h"
class CMyApp : public CWinApp {
};
extern CMyApp g_myApp;
5.CMyApp.h中写上虚函数InitInstance的声明
#pragma once
#include "framework.h"
class CMyApp : public CWinApp {
public:
virtual BOOL InitInstance() override;
private:
};
extern CMyApp g_myApp;
6.CMyApp.cpp中重写虚函数InitInstance
#include "CMyApp.h"
#include "CMyDlg.h"
BOOL CMyApp::InitInstance() {
CMyDlg dlg;
dlg.DoModal();
return 0;
}
CMyApp g_myApp;
7.CMyDlg提供构造函数
//CMyDlg.h文件
#pragma once
#include "framework.h"
#include "resource.h"
class CMyDlg :public CDialogEx {
public :
CMyDlg(CWnd *pParent = nullptr);
};
//CMyDlg.cpp文件
#include "CMyDlg.h"
CMyDlg::CMyDlg(CWnd *pParent):CDialogEx(IDD_DIALOG1, pParent) {
//IDD_DIALOG1是自己添加的对话框的资源ID
}
到此程序可以运行了。
8.下面来实现双击控件自动生成代码的功能
//CMyDlg.h文件
#pragma once
#include "framework.h"
#include "resource.h"
class CMyDlg :public CDialogEx {
public :
CMyDlg(CWnd *pParent = nullptr);
// 对话框数据,加上此宏可以双击控件自动生成代码
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG1 };
#endif
};
9.资源视图增加一个按钮,双击按钮,自动生成了代码,如下所示
//CMyDlg.h文件
#pragma once
#include "framework.h"
#include "resource.h"
class CMyDlg :public CDialogEx {
// 对话框数据,加上此宏可以双击控件自动生成代码
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG1 };
#endif
public:
CMyDlg(CWnd *pParent = nullptr);
//自动生成的
DECLARE_MESSAGE_MAP()
afx_msg void OnBnClickedButton1();
};
//CMyDlg.cpp文件
#include "CMyDlg.h"
CMyDlg::CMyDlg(CWnd *pParent):CDialogEx(IDD_DIALOG1, pParent) {
}
//自动生成的消息映射表
BEGIN_MESSAGE_MAP(CMyDlg, CDialogEx)
ON_BN_CLICKED(IDC_BUTTON1, &CMyDlg::OnBnClickedButton1)
END_MESSAGE_MAP()
//自动生成的处理函数,函数体自己填写代码
void CMyDlg::OnBnClickedButton1() {
AfxMessageBox(L"Hello");
}
10.运行,点击按钮,可以弹窗。
11.添加自定义消息
在资源对话框上右键,选择添加类向导,弹出界面,点击“添加自定义消息”


确定之后,自动生成了代码,如下图红框中所示。

第21行的宏vs不认识,手动#define WM_MYMGS WM_USER+1即可。调用SendMessage发送自定义消息。

浙公网安备 33010602011771号