初识Win32窗口应用程序(一)

刚接触windows窗口程序记录主要两个函数


1.#include <windows.h>

窗口程序的重要头文件,必须导入

2.WinMain()

窗口主函数入口,此函数负责窗口属性的初始化,显示,更新,和消息分发的

int WINAPI WinMain(
	 HINSTANCE hInstance,//应用程序实例句柄
	 HINSTANCE hPrevInstance,//上一个应用程序句柄,在win32环境下,参数一般为null
	 LPSTR lpCmdLine,	 int nShowCmd) ;

3.WindowProc()

此函数是消息处理函数,负责事件处理,比如窗口内容展示,窗口的按钮关闭等

LRESULT CALLBACK WindowProc(HWND hwnd,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam);

4.完整示例代码

#include <windows.h>
  //消息处理函数LRESULT CALLBACK WindowProc(HWND hwnd,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam
) {	int xPos, yPos;	char buf[100];
	PAINTSTRUCT ps;
	HDC hdc;	switch (uMsg)
	{	case WM_CLOSE:
		DestroyWindow(hwnd); //关闭窗口
		break;	case WM_DESTROY:
		PostQuitMessage(0);//退出程序
		break;	case WM_KEYDOWN:
		wsprintf(buf, TEXT("键盘ASCII = %d"), wParam);
		MessageBox(hwnd, buf, TEXT("键盘"), MB_OK);		break;	case WM_LBUTTONDOWN:
		xPos = LOWORD(lParam);
		yPos = HIWORD(lParam);
		wsprintf(buf, TEXT("X = %d,Y = %d"), xPos,yPos);
		MessageBox(hwnd, buf, TEXT("鼠标"), MB_OK);		break;	case WM_PAINT: 
		hdc = BeginPaint(hwnd, // handle to window
						&ps); // paint information);
		TextOut(hdc,0,0,TEXT("text"),strlen("text"));
		EndPaint(hwnd, &ps);		break;	default:		break;
	}	return DefWindowProc(hwnd, uMsg, wParam, lParam);
}int WINAPI WinMain(//窗口主函数入口
	HINSTANCE hInstance,//应用程序实例句柄
	HINSTANCE hPrevInstance,//上一个应用程序句柄,在win32环境下,参数一般为null
	LPSTR lpCmdLine,	int nShowCmd) //最大化 最小化{

	WNDCLASS wc;

	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hbrBackground = GetStockObject(WHITE_BRUSH);
	wc.hCursor = LoadCursor(NULL, IDC_HAND);
	wc.hIcon = LoadIcon(NULL, IDI_INFORMATION);
	wc.hInstance = hInstance;
	wc.lpfnWndProc = WindowProc;
	wc.lpszClassName = TEXT("WIN");
	wc.lpszMenuName = NULL;
	wc.style = 0;

	RegisterClass(&wc);//注册

	HWND  hwnd = CreateWindow(
		wc.lpszClassName, //lpClassName
		TEXT("Hello"),   //lpWindowName
		WS_OVERLAPPEDWINDOW, //dwStyle
		CW_USEDEFAULT, //x, 
		CW_USEDEFAULT, //y,
		CW_USEDEFAULT, //nWidth
		CW_USEDEFAULT,//nHeight
		NULL,//hWndParent
		NULL,//hMenu
		hInstance,//hInstance
		NULL);//lpParam

	ShowWindow(hwnd, SW_SHOWNORMAL);

	UpdateWindow(hwnd);

	MSG msg;	while (1)
	{		if (GetMessage(&msg, NULL, 0, 0) == FALSE) {			break;
		}

		TranslateMessage(&msg);
		DispatchMessage(&msg);

	}  return 0;
}

5. Visual Studio代码结构 mWindows.c

初识Win32窗口应用程序(一)




初识Win32窗口应用程序(一)


6.运行效果

初识Win32窗口应用程序(一)


初识Win32窗口应用程序(一)


Thanks