前面介绍到了注册窗口,接下来进行窗口的创建,利用CreateWindow函数,结构如下
CreateWindowExW( DWORD dwExStyle, LPCWSTR lpClassName, //指定窗口类的名称 LPCWSTR lpWindowName, //窗口名字 DWORD dwStyle, //窗口的样式 WS_xxx int X, //x坐标 int Y, //y坐标 int nWidth, //宽度 int nHeight, //高度 HWND hWndParent , //父窗口句柄 HMENU hMenu, //窗口菜单句柄 HINSTANCE hInstance, //窗口实例句柄 LPVOID lpParam); //大都设置为NULL #ifdef UNICODE #define CreateWindowEx CreateWindowExW #else #define CreateWindowEx CreateWindowExA #endif // !UNICODE
窗口创建完成。接下来显示和更新窗口,结构分别如下
ShowWindow( HWND hWnd, //创建窗口成功后返回的窗口句柄 int nCmdShow);//窗口显示的状态SW_XXXX
UpdateWindow( HWND hWnd); //创建窗口成功后返回的窗口句柄
接下来就是消息循环了。getMessage函数,结构如下
GetMessageW( LPMSG lpMsg, //指向MSG消息结构体 HWND hWnd , //指向窗口句柄,NULL代表接受所有的窗口信息 UINT wMsgFilterMin, //0 UINT wMsgFilterMax); //0 #ifdef UNICODE #define GetMessage GetMessageW #else #define GetMessage GetMessageA #endif // !UNICODE
使用方法如下:
MSG msg; while (GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); }
接下来就是前面所提到的窗口过程函数,如下
LRESULT CALLBACK WinSunProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); //窗口句柄,消息,两个附加信息
说了这么多,总结一下,窗口创建过程,就这几步骤
1.WinMain函数定义
2.设计一个窗口类
3.注册窗口类
4.创建窗口类
5.显示及更新窗口
6.进行消息寻环
7.编写窗口过程函数
下面贴上完整的代码:
#include <windows.h> #include <stdio.h> LRESULT CALLBACK WinSunProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd ){ //设计一个窗口类 WNDCLASS wndcls; wndcls.cbClsExtra = 0; wndcls.cbWndExtra = 0; wndcls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndcls.hIcon = LoadIcon(NULL,IDI_ERROR); wndcls.hCursor = LoadCursor(NULL,IDC_CROSS); wndcls.hInstance = hInstance; //用用程序实例句柄由WinMain函数传过来 wndcls.lpfnWndProc = WinSunProc; wndcls.lpszClassName = "刘凯"; wndcls.lpszMenuName = NULL; wndcls.style = CS_HREDRAW | CS_VREDRAW; RegisterClass(&wndcls); //创建窗口,定义一个变量用来保存成功创建窗口后返回的句柄 HWND hwnd; hwnd = CreateWindow("刘凯","第一个窗体", 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 msg.wParam; } //编写窗口过程函数 LRESULT CALLBACK WinSunProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ){ switch (uMsg) { case WM_CHAR : char szChar[20]; sprintf(szChar,"char code is %d",wParam); MessageBox(hwnd,szChar,"char",0); break; case WM_LBUTTONDBLCLK : MessageBox(hwnd,"mouse clicked","message",0); HDC hdc; hdc = GetDC(hwnd); //不能在相应WM_PAINT消息时调用 TextOut(hdc,0,50,"程序之家",strlen("程序之家")); break; case WM_PAINT : HDC hDC; PAINTSTRUCT ps; hDC = BeginPaint(hwnd,&ps); //BeginPaint只能在响应WM_PAINT消息时调用 TextOut(hDC,0,0,"http://www.baidu.com",strlen("http://www.baidu.com")); EndPaint(hwnd,&ps); break; case WM_CLOSE : if (IDYES == MessageBox(hwnd,"是否真的结束?","message",MB_YESNO)) { DestroyWindow(hwnd); } break; case WM_DESTROY : PostQuitMessage(0); break; default: return DefWindowProc(hwnd,uMsg,wParam,lParam); } return 0; }