MFC第一个例子 -- windows程序运行原理

时间:2022-03-31 21:29:45
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#pragma comment  (lib,"User32.lib")
#pragma comment  (lib,"Gdi32.lib")
LRESULT CALLBACK WinSunProc(
  HWND hwnd,      // handle to window
  UINT uMsg,      // message identifier
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
);

int WINAPI WinMain(
  HINSTANCE hInstance,      // handle to current instance
  HINSTANCE hPrevInstance,  // handle to previous instance
  LPSTR lpCmdLine,          // command line
  int nCmdShow              // show state
)//windows入口地址
{
	WNDCLASS wndcls;//窗口类
	wndcls.cbClsExtra=0;
	wndcls.cbWndExtra=0;
	wndcls.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);
	wndcls.hCursor=LoadCursor(NULL,IDC_CROSS);
	wndcls.hIcon=LoadIcon(NULL,IDI_APPLICATION);
	wndcls.hInstance=hInstance;
	wndcls.lpfnWndProc=WinSunProc;//回调函数
	wndcls.lpszClassName=_T("Weixin2003");
	wndcls.lpszMenuName=NULL;
	wndcls.style=CS_HREDRAW | CS_VREDRAW;
	RegisterClass(&wndcls);

	HWND hwnd;
	hwnd=CreateWindow(_T("Weixin2003"),
	  _T("北京维新科学技术培训中心"),
	  WS_OVERLAPPEDWINDOW ,
		0,
		0,
		600,
		400,
		NULL,
		NULL,
		hInstance	,
		NULL);

	ShowWindow(hwnd,SW_SHOWNORMAL);//显示窗口
	UpdateWindow(hwnd);//窗口的刷新

	MSG msg;//消息结构体的变量
	while(GetMessage(&msg,NULL,0,0))
	{
		TranslateMessage(&msg);//对取到的消息对进行转换,
		DispatchMessage(&msg);//将消息给操作系统,调用回调函数进行处理
	}
	return 0;
}

LRESULT CALLBACK WinSunProc(
  HWND hwnd,      // handle to window
  UINT uMsg,      // message identifier
  WPARAM wParam,  // first message parameter
  LPARAM lParam   // second message parameter
)
{
	switch(uMsg)
	{
	case WM_CHAR:
		TCHAR szChar[20];
		sprintf(szChar,"char is %d",wParam);
		MessageBox	//创建消息框
		  (hwnd,//窗口的句柄
		  szChar//消息显示文本
		  ,_T("weixin")//标题
		  ,MB_YESNO);//消息框的类型
		break;
	case WM_LBUTTONDOWN:
		MessageBox(hwnd,_T("mouse clicked"),_T("weixin"),0);
		HDC hdc;//DC(Device Context) 句柄,帮助完成绘制动作,程序中作图
		hdc=GetDC(hwnd);//窗口的句柄,获得DC
		TextOut(hdc,0,50,_T("计算机编程语言培训"),strlen("计算机编程语言培训"));//文本输出
		ReleaseDC(hwnd,hdc);//释放DC,DC要占用内存,因此必须要释放DC
		break;
	  case WM_PAINT:
		HDC hDC;
		PAINTSTRUCT ps;
		hDC=BeginPaint(hwnd,&ps);
		TextOut(hDC,0,0,_T("BJ维新培训"),strlen("BJ维新培训"));
		EndPaint(hwnd,&ps);//释放内存 DC
		break;
	case WM_CLOSE:
		if(IDYES ==MessageBox(hwnd,_T("是否真的结束?"),_T("weixin"),MB_YESNO))//返回值为IDYES,则窗口关闭
		{
			DestroyWindow(hwnd);//给windows发布WM_DESTROY and WM_NCDESTROY消息
		}
		break;
	case WM_DESTROY:
		PostQuitMessage(0);//将窗口销毁,使 WM_QUIT为0,则使GetMessage为0,调成while()函数并且返回0值,则WinMain()函数终止
		break;
	default:
		return DefWindowProc(hwnd,uMsg,wParam,lParam);//缺省窗口过程,对其他不感兴趣的过程处理
	}
	return 0;
}