MFC 프로그램의 구조
Microsoft Foundation Classes (MFC) 라이브러리는 C++ 기반의 윈도우 애플리케이션을 개발하기 위한 클래스 라이브러리입니다. MFC를 사용하면 Win32 API의 복잡한 작업을 간소화할 수 있으며, 객체 지향적으로 윈도우 애플리케이션을 개발할 수 있습니다. MFC 프로그램의 구조는 일반적인 Win32 애플리케이션과는 다르게 클래스와 메시지 맵을 사용하여 구성됩니다.
MFC 프로그램의 기본 구조
헤더 파일 포함
MFC를 사용하려면, MFC 라이브러리를 포함하는 헤더 파일을 포함해야 합니다.
cpp
코드 복사
#include <afxwin.h> // MFC의 핵심 헤더 파일
애플리케이션 클래스 정의
MFC 애플리케이션은 CWinApp 클래스를 상속하여 애플리케이션의 초기화와 종료를 처리하는 클래스를 정의합니다. 이 클래스는 애플리케이션의 전역적인 기능을 설정합니다.
cpp
코드 복사
class CMyApp : public CWinApp {
public:
virtual BOOL InitInstance();
};
CMyApp theApp; // 애플리케이션 객체
윈도우 클래스 및 윈도우 정의
MFC 애플리케이션은 CFrameWnd 또는 CDialog 클래스를 상속하여 주 윈도우 또는 대화 상자를 정의합니다. CMainFrame 클래스는 주 윈도우의 기능을 정의합니다.
cpp
코드 복사
class CMainFrame : public CFrameWnd {
public:
CMainFrame();
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
};
메시지 맵
MFC에서는 메시지 맵을 사용하여 윈도우 메시지를 처리합니다. 메시지 맵은 메시지와 메시지를 처리하는 함수 간의 연결을 설정합니다.
cpp
코드 복사
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_WM_PAINT()
END_MESSAGE_MAP()
애플리케이션 초기화
InitInstance 메서드는 애플리케이션의 초기화 작업을 수행합니다. 여기에서 주 윈도우를 생성하고 표시하는 작업을 수행합니다.
cpp
코드 복사
BOOL CMyApp::InitInstance() {
CMainFrame* pMainFrame = new CMainFrame;
m_pMainWnd = pMainFrame;
pMainFrame->Create(NULL, _T("MFC Sample Application"));
pMainFrame->ShowWindow(SW_NORMAL);
pMainFrame->UpdateWindow();
return TRUE;
}
주 클래스 구현
CMainFrame 클래스에서 메시지를 처리하는 함수들을 구현합니다.
cpp
코드 복사
CMainFrame::CMainFrame() {
// 프레임 윈도우 초기화 작업
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
return 0;
}
void CMainFrame::OnPaint() {
CPaintDC dc(this);
// 그리기 작업
}
전체 코드 예제
다음은 MFC를 사용한 기본적인 윈도우 애플리케이션의 전체 코드 예제입니다.
cpp
코드 복사
#include <afxwin.h> // MFC 헤더 파일
class CMyApp : public CWinApp {
public:
virtual BOOL InitInstance();
};
class CMainFrame : public CFrameWnd {
public:
CMainFrame();
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
ON_WM_PAINT()
END_MESSAGE_MAP()
CMainFrame::CMainFrame() {
// 프레임 윈도우 초기화 작업
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) {
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
return 0;
}
void CMainFrame::OnPaint() {
CPaintDC dc(this);
// 그리기 작업
}
BOOL CMyApp::InitInstance() {
CMainFrame* pMainFrame = new CMainFrame;
m_pMainWnd = pMainFrame;
pMainFrame->Create(NULL, _T("MFC Sample Application"));
pMainFrame->ShowWindow(SW_NORMAL);
pMainFrame->UpdateWindow();
return TRUE;
}
CMyApp theApp; // 애플리케이션 객체
주요 구성 요소
애플리케이션 클래스 (CMyApp): 애플리케이션의 전반적인 초기화 및 종료 작업을 처리합니다.
주 윈도우 클래스 (CMainFrame): 주 윈도우의 생성 및 메시지 처리를 담당합니다.
메시지 맵: 윈도우에서 발생하는 메시지를 처리하는 함수와 연결합니다.
애플리케이션 초기화: InitInstance 메서드에서 애플리케이션의 초기화를 수행합니다.
이러한 구조를 바탕으로 MFC를 사용하여 윈도우 애플리케이션을 개발할 수 있으며, 복잡한 사용자 인터페이스와 기능을 효과적으로 구현할 수 있습니다.