吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 573|回复: 3
上一主题 下一主题
收起左侧

[C&C++ 原创] MFC命令路由机制

[复制链接]
跳转到指定楼层
楼主
lrj2025kernel 发表于 2026-8-14 15:42 回帖奖励
[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;

#define ID_OPEN  100
#define ID_SAVE  101
#define ID_EXIT  102

class CCmdTarget
{
public:
	//要声明为虚函数,形成多态
	virtual bool OnCmdMsg(int id)
	{
		return false;
	}
};

class CDocument : public CCmdTarget
{
public:
	bool OnCmdMsg(int id) override
	{
		if (id == ID_SAVE)
		{
			cout << "CDocument::OnSave()" << endl;
			return true;
		}

		return CCmdTarget::OnCmdMsg(id);
	}
};

class CView : public CCmdTarget
{
	CDocument* m_pDoc;

public:
	CView(CDocument* doc) : m_pDoc(doc) {}

	bool OnCmdMsg(int id) override
	{
		cout << "CView::OnCmdMsg()" << endl;

		if (id == ID_OPEN)
		{
			cout << "CView::OnOpen()" << endl;
			return true;
		}

		// View 自己不处理
		// 转给 Document
		if (m_pDoc->OnCmdMsg(id))
			return true;

		return CCmdTarget::OnCmdMsg(id);
	}
};

class CWinApp : public CCmdTarget
{
public:
	bool OnCmdMsg(int id) override
	{
		if (id == ID_EXIT)
		{
			cout << "CWinApp::OnExit()" << endl;
			return true;
		}

		return CCmdTarget::OnCmdMsg(id);
	}
};

class CFrameWnd : public CCmdTarget
{
	CView* m_pView;
	CWinApp* m_pApp;

public:
	CFrameWnd(CView* view, CWinApp* app)
		: m_pView(view), m_pApp(app) {
	}

	bool OnCommand(int id)
	{
		cout << "CFrameWnd::OnCommand()" << endl;

		return OnCmdMsg(id);
	}

	bool OnCmdMsg(int id) override
	{
		cout << "CFrameWnd::OnCmdMsg()" << endl;

		// ① View
		if (m_pView->OnCmdMsg(id))
			return true;

		// ② Frame 自己
		if (CCmdTarget::OnCmdMsg(id))
			return true;

		// ③ App
		if (m_pApp->OnCmdMsg(id))
			return true;

		return false;
	}
};

int main()
{
	CWinApp app;
	CDocument doc;
	CView view(&doc);
	//这里暂时传入CView,实际中很可能是CView的派生类
	CFrameWnd frame(&view, &app);

	cout << "---- ID_OPEN ----" << endl;
	frame.OnCommand(ID_OPEN);

	cout << "\n---- ID_SAVE ----" << endl;
	frame.OnCommand(ID_SAVE);

	cout << "\n---- ID_EXIT ----" << endl;
	frame.OnCommand(ID_EXIT);

	cout << "\n---- ID_UNKNOWN ----" << endl;
	frame.OnCommand(999);

	system("pause");

	return 0;
}

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
over1225 + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

沙发
bytebate 发表于 2026-8-14 16:57
不错,加油!
3#
ITHM 发表于 2026-8-15 09:54
4#
zilong1988 发表于 2026-8-15 15:23
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-8-17 02:01

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表