初探C++ win32 api——Hello world!

win32 api 试水——Helloworld

(可能是因为用的MingGW,会出现一些奇怪的问题比如MSDN的示例代码过不了编译之类的。。。。。)
编译器版本:

fig1

#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif

#include <windows.h>

HINSTANCE hInst;
HWND hwndMain;
WNDCLASS wcMain;

LRESULT CALLBACK mainProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, INT nCmdShow) {
	//隐藏命令行窗口
	FreeConsole();

	//句柄存成全局是因为有可能过程函数要用到
	hInst = hInstance;

	//设计窗口类
	wcMain.hInstance = hInst;
	wcMain.lpszClassName = L"MainWindow";
	wcMain.lpfnWndProc = mainProc;

	//注册窗口类
	RegisterClass(&wcMain);

	//创建窗口
	hwndMain = CreateWindow(L"MainWindow", L"Main", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 700, 450, NULL, NULL, hInst, NULL);

	//显示,更新窗口
	ShowWindow(hwndMain, SW_SHOW);
	UpdateWindow(hwndMain);

	//消息循环
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return 0;
}

LRESULT CALLBACK mainProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg) {
		case WM_KEYDOWN : { //任意键被按下时
			if (wParam == VK_ESCAPE) SendMessage(hwnd, WM_CLOSE, NULL, NULL); //如果是ESC就关闭窗口
			else MessageBox(NULL, L"Hello world!", L"Message", MB_OK); //否则弹出一个对话框
			break;
		}
		case WM_DESTROY : {
			PostQuitMessage(0); //发送WM_QUIT消息
			break;
		}
		default : {
			return DefWindowProc(hwnd, msg, wParam, lParam); //其它消息用默认方式处理
		}
	}
	return 0;
}
posted @ 2020-12-17 22:30  Rhein_E  阅读(471)  评论(0编辑  收藏  举报