1.定义窗口类
2.注册窗口
3.创建窗口
4.显示窗口
5.消息循环
6.获取消息
首先得创建一个函数指针
LRESULT WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
return DefWindowProc(hwnd, message, wparam, lparam);
}
1.定义窗口类
WNDCLASS wc; // EX
wc.cbClsExtra = NULL; // 忽略: 窗口类附加数据缓冲区.
wc.cbWndExtra = NULL; // 忽略: 窗口附加数据缓冲区
wc.hInstance = hInstanc; //实例句柄
wc.hbrBackground = NULL; // 窗口背景
wc.hCursor = NULL;// 光标
wc.hIcon = NULL; //图标
wc.lpfnWndProc = (WNDPROC)WndProc; //????
wc.lpszClassName = _T("mywin");
wc.lpszMenuName = NULL;
wc.style = NULL;//风格
2.注册窗口
RegisterClass(&wc);
3.创建窗口
HWND hwnd;
hwnd = CreateWindow(wc.lpszClassName, _T("我的窗口"), WS_OVERLAPPEDWINDOW, 100, 100, 400, 500, nullptr, nullptr, hInstance, nullptr);
4.显示窗口
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
5.消息循环
while (GetMessage(&msg, hwnd,NULL,0))//6.1获取消息
{
TranslateMessage(&msg);//6.2翻译消息
DispatchMessage(&msg);//6.3消息派发
}
代码+运行结果:
#include<Windows.h>
#include<tchar.h>
LRESULT WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
return DefWindowProc(hwnd, message, wparam, lparam);
}
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hpInstance,
LPSTR cmd,
int show)
{
//1.设计窗口
WNDCLASS wc;
wc.style = CS_HREDRAW;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.lpszMenuName = nullptr;
wc.lpszClassName = _T("HelloWorld");
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.hInstance = hInstance;
wc.hIcon = nullptr;
wc.hCursor = nullptr;
wc.hbrBackground = nullptr;
//2.注册窗口
RegisterClass(&wc);
//3.创建窗口
HWND hwnd;
hwnd = CreateWindow(wc.lpszClassName, _T("我的窗口"), WS_OVERLAPPEDWINDOW, 100, 100, 400, 500, nullptr, nullptr, hInstance, nullptr);
//4.显示窗口
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
//5.获取消息
MSG msg = { 0 };
//6.消息循环
while (GetMessage(&msg, hwnd,NULL,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}