winapp | 用win32api创建窗口程序

主要的过程都写在下面代码中的注释里啦:

// windowsapp.cpp : Defines the entry point for the application.
//

#include "stdafx.h"

LRESULT CALLBACK WindowProc(HWND hwnd,
							UINT uMsg,
							WPARAM wParam,
							LPARAM LParam){
	// 窗口程序
	// 处理消息队列的消息
	switch (uMsg)
	{
	case WM_DESTROY:
		PostQuitMessage(0);    // 让当前程序退出
		return 0;
	}

	return DefWindowProc(hwnd, uMsg, wParam, LParam); // 调用默认的消息处理函数
}


int APIENTRY WinMain(HINSTANCE hInstance,           // 句柄 模块的起始位置
                     HINSTANCE hPrevInstance,       // 永远为空
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	/*
	DWORD dwAddr = (DWORD)hInstance;
	char szOutBuff[0x80];
	sprintf(szOutBuff, "module place: 0x%X \n", dwAddr);   // 打印模块起始地址
	OutputDebugString(szOutBuff);
	*/
	
	// 第一步:定义窗口是什么样的
	TCHAR className[] = TEXT("My first Window");
	WNDCLASS wndclass = {0};                // 窗口类初始化
	wndclass.hbrBackground = (HBRUSH)COLOR_BACKGROUND;//背景色
	wndclass.lpszClassName = className;             // 窗口类名
	wndclass.hInstance = hInstance;               // 窗口是属于哪个程序的
	wndclass.lpfnWndProc = WindowProc;            // 窗口程序(窗口过程函数地址)

	// 第二步:注册窗口类
	RegisterClass(&wndclass);        // 让操作系统知道你这个窗口

	// 第三步:创建并显示窗口
	HWND hwnd = CreateWindow(
		className,                             // 注册的类名
		TEXT("我的第一个窗口"),                 // 窗口名
		WS_OVERLAPPEDWINDOW,                   // 窗口风格
		10,
		10,                                   // 相对于父窗口的x,y坐标
		600,
		300,                                 // 宽高
		NULL,                                  // 父窗口的句柄
		NULL,                                 // 菜单句柄
		hInstance,                        // 是属于哪个模块的
		NULL                              // 附加数据 空
		);

	// 第四步:显示窗口
	ShowWindow(hwnd, SW_SHOW);         // 默认形式显示

	// 第五步:接收消息并处理
	MSG msg;          // 用于接收消息的结构体
	BOOL bRet; 
	while((bRet = GetMessage( &msg, NULL, 0, 0)) != 0){// 参数2:取哪个窗口的消息,如果为空,就是取所有的
		if (bRet == -1){
			// handle the error
		}else{
			TranslateMessage(&msg); // 转换消息
			DispatchMessage(&msg);   // 分发消息 给消息处理函数处理
		}
	}
	return 0;
}
posted @ 2021-08-19 14:57  Mz1  阅读(166)  评论(0编辑  收藏  举报