我创建了一个Win32控制台应用程序来编写一个简单的MFC项目。
源代码如下:
#include <afxwin.h>
class MyApp : public CWinApp
{
public:
BOOL InitInstance();
MyApp()
{
}
};
class MainWindow : public CFrameWnd
{
protected:
int OnCreate(LPCREATESTRUCT lpCreateStruct);
void OnClose();
LRESULT OnTimer(WPARAM wParam, LPARAM lParam);
// This line is causing the error
DECLARE_MESSAGE_MAP()
};
BOOL MyApp::InitInstance()
{
MainWindow* mainWindow = new MainWindow();
m_pMainWnd = mainWindow;
mainWindow->Create(NULL, L"Main Window");
mainWindow->ShowWindow(m_nCmdShow);
return TRUE;
}
MyApp myApp;
int MainWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
SetTimer(1, 2000, NULL);
return 0;
}
void MainWindow::OnClose()
{
if (MessageBox(L"Close?", L"Close", MB_YESNO | MB_ICONQUESTION) == IDYES)
{
KillTimer(1);
CFrameWnd::OnClose();
}
}
LRESULT MainWindow::OnTimer(WPARAM wParam, LPARAM lParam)
{
MessageBeep(MB_ICONQUESTION);
return 0;
}
当我尝试编译时,我收到以下错误:
错误1错误LNK2001:未解析的外部符号“protected:virtual struct AFX_MSGMAP const * __thiscall MainWindow :: GetMessageMap(void)const”(?GetMessageMap @ MainWindow @@ MBEPBUAFX_MSGMAP @@ XZ)D:\ Projects \ MinimumMFC \ MinimumMFC \ MinimumMFC.obj MinimumMFC
答案 0 :(得分:1)
我忘了在MainWindow声明之后声明BEGIN_MESSAGE_MAP:
BEGIN_MESSAGE_MAP(MainWindow, CFrameWnd)
ON_WM_CREATE()
ON_WM_CLOSE()
ON_MESSAGE(WM_TIMER, OnTimer)
END_MESSAGE_MAP()
完整的源代码应该是:
#include <afxwin.h>
class MyApp : public CWinApp
{
public:
BOOL InitInstance();
MyApp()
{
}
};
class MainWindow : public CFrameWnd
{
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnClose();
afx_msg LRESULT OnTimer(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(MainWindow, CFrameWnd)
ON_WM_CREATE()
ON_WM_CLOSE()
ON_MESSAGE(WM_TIMER, OnTimer)
END_MESSAGE_MAP()
BOOL MyApp::InitInstance()
{
MainWindow* mainWindow = new MainWindow();
m_pMainWnd = mainWindow;
mainWindow->Create(NULL, L"Main Window");
mainWindow->ShowWindow(m_nCmdShow);
return TRUE;
}
MyApp myApp;
int MainWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
SetTimer(1, 2000, NULL);
return 0;
}
void MainWindow::OnClose()
{
if (MessageBox(L"Close?", L"Close", MB_YESNO | MB_ICONQUESTION) == IDYES)
{
KillTimer(1);
CFrameWnd::OnClose();
}
}
LRESULT MainWindow::OnTimer(WPARAM wParam, LPARAM lParam)
{
MessageBeep(MB_ICONQUESTION);
return 0;
}