参照孙鑫《VC++深入详解》
创建Win32程序的步骤:
1、 编写WinMain函数
2、 设计窗口类(WNDCLASS)
3、 注册窗口类
4、 创建窗口
5、 显示并更新窗口(ShowWindow(hwnd,SW_SHOWNORMAL);UpdateWindow(hwnd);)
6、 消息循环(不断地从消息队列中取出消息,并进行响应)
7、 窗口过程函数(处理发送给窗口的消息)
测试代码如下(在VS2010编译通过):
#include <stdafx.h> #include <windows.h> #include <stdio.h> LRESULT CALLBACK WinProc( 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.hCursor = LoadCursor(NULL,IDC_CROSS); wndcls.hIcon = LoadIcon(NULL,IDI_ERROR); wndcls.hInstance = hInstance; wndcls.lpfnWndProc = WinProc; wndcls.lpszClassName = _T("window"); wndcls.lpszMenuName = NULL; wndcls.style = CS_HREDRAW | CS_VREDRAW; RegisterClass(&wndcls); //创建窗口,定义一个变量用来保存成功创建窗口后返回的句柄 HWND hwnd; hwnd = CreateWindow(_T("window"),_T("window"),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 WinProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { switch(uMsg) { case WM_CHAR: char szChar[20]; sprintf_s(szChar,"you pressed %d",wParam); MessageBoxA(hwnd,szChar,"char",0); break; case WM_LBUTTONDOWN: MessageBox(hwnd,_T("mouse clicked"),_T("message"),0); HDC hdc; hdc = GetDC(hwnd); TextOut(hdc,0,100,_T("WM_LBUTTONDOWN消息"),strlen("WM_LBUTTONDOWN消息")); ReleaseDC(hwnd, hdc); break; case WM_PAINT: HDC Paint_Hdc; PAINTSTRUCT ps; Paint_Hdc = BeginPaint(hwnd,&ps); TextOut(Paint_Hdc,0,0,_T("WM_PAINT消息"),strlen("WM_PAINT消息")); EndPaint(hwnd,&ps); break; case WM_CLOSE: if (IDYES == MessageBox(hwnd,_T("是否真的结束?"),_T("message"),MB_YESNO)) { DestroyWindow(hwnd); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd,uMsg,wParam,lParam); } return 0; }
1、 对于以下语句:
char szChar[20];
sprintf_s(szChar,"you pressed %d",wParam);
MessageBox(hwnd,szChar,"char",0);
编译报错:不能将参数 2 从“char [20]”转换为“LPCWSTR”
这是由于工程使用了UNICODE字符集 ,可使用_T(" ")转换,但是_T(" ")对变量不起作用。
将MessageBox变为MessageBoxA,参数为短字符。
运行截图
再理解Windows程序内部运行机制,布布扣,bubuko.com
时间: 2024-10-03 22:39:52