学MFC应该先从Win32 Application学起,这样才能更清楚MFC的运行机制和原理。下面贴两个代码,共感兴趣的朋友学习参考之用。
第一个:
#include "windows.h"
LRESULT CALLBACK WindowProc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd)
{
WNDCLASSEX window;
window.cbClsExtra=0;
window.cbSize=sizeof(WNDCLASSEX);
window.cbWndExtra=0;
window.hbrBackground=static_cast<HBRUSH>(GetStockObject(DKGRAY_BRUSH));
window.hCursor=LoadCursor(NULL,IDC_ARROW);
window.hIcon=LoadIcon(NULL,IDI_APPLICATION);
window.hIconSm=NULL;
window.hInstance=hInstance;
window.lpfnWndProc=WindowProc;
window.lpszClassName=L"MyWindow";
window.lpszMenuName=NULL;
window.style=CS_VREDRAW | CS_HREDRAW;
RegisterClassEx(&window);
HWND hwnd;
hwnd=CreateWindowEx(0,L"MyWindow",L"诗一句",WS_OVERLAPPEDWINDOW,0,0,600,400,NULL,NULL,hInstance,NULL);
ShowWindow(hwnd,nShowCmd);
UpdateWindow(hwnd);
MSG msg;
while(GetMessage(&msg,NULL,NULL,NULL))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam)
{
RECT rect;
HDC hdc;
PAINTSTRUCT PaintST;
switch(uMsg)
{
case WM_PAINT:
hdc=BeginPaint(hwnd,&PaintST);
GetClientRect(hwnd,&rect);
SetBkMode(hdc,TRANSPARENT);
DrawText(hdc,L"再牛逼的萧邦也弹奏不出我的哀伤!",-1,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
EndPaint(hwnd,&PaintST);
break;
case WM_CLOSE:
if(IDYES==MessageBox(hwnd,L"这么有深意的诗你确定不看了?",L"无限哀伤",MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}
第二个:
#include "afxwin.h"
class COurWnd:public CFrameWnd
{
public:
COurWnd()
{
Create(0,L"无尽哀伤");
}
};
class COurApp:public CWinApp
{
public:
virtual BOOL InitInstance()
{
COurApp::m_pMainWnd=new COurWnd;
COurApp::m_pMainWnd->ShowWindow(m_nCmdShow);
return TRUE;
}
};
COurApp application;
这两个程序都在Visual C++2005下运行验证过。