MFC 應用程式框架默認使用 `WinMain` 作為入口點,並由 `CWinApp` 派生類管理初始化流程。若需插入自定義的 `main()` 函數(如控制台混合模式、特殊初始化邏輯),必須重定義入口點。
// 自定義入口點
int MyMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 1. 初始化 MFC 狀態
if (!AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nCmdShow))
{
return FALSE;
}
// 2. 執行自定義邏輯(如控制台分配、配置讀取等)
AllocConsole();
freopen("CONOUT$", "w", stdout);
printf("Custom initialization...\n");
// 3. 創建並運行應用程式物件
CMyApp theApp; // 你的 CWinApp 派生類
return theApp.Run();
}
// 禁用默認 WinMain
// 專案屬性 -> Linker -> System -> SubSystem: Console (/SUBSYSTEM:CONSOLE)
// 或在 stdafx.h 前添加:
// #define _AFXDLL
// #pragma comment(linker, "/subsystem:console /entry:MyMain")
詳細步驟請參考:CSDN 博客:重定義 MFC 函數入口點
提示: 現代 MFC 開發極少需要自定義 `main`。若需控制台輔助調試,建議在 `InitInstance()` 中調用 `AllocConsole()`,保持標準框架流程不變。