您好,使用GetMessage接受消息,再通过CALLBACK WndProc回调分别处理不同的消息即可实现你想要的效果,您应该是在学习基本的消息循环机制吧,给你一段完整的演示案例,您可以编译运行试试。
#include <Windows.h>
// 按钮的标识符
#define BUTTON_YES 1
#define BUTTON_NO 2
#define BUTTON_CANCEL 3
// 消息处理函数
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
// 创建按钮
CreateWindowW(L"BUTTON", L"Yes", WS_VISIBLE | WS_CHILD, 10, 10, 100, 30, hwnd, (HMENU)BUTTON_YES, NULL, NULL);
CreateWindowW(L"BUTTON", L"No", WS_VISIBLE | WS_CHILD, 10, 50, 100, 30, hwnd, (HMENU)BUTTON_NO, NULL, NULL);
CreateWindowW(L"BUTTON", L"Cancel", WS_VISIBLE | WS_CHILD, 10, 90, 100, 30, hwnd, (HMENU)BUTTON_CANCEL, NULL, NULL);
break;
case WM_COMMAND:
{
int buttonId = LOWORD(wParam);
switch (buttonId)
{
case BUTTON_YES:
MessageBoxW(hwnd, L"你按下了是按钮", L"消息", MB_OK);
break;
case BUTTON_NO:
MessageBoxW(hwnd, L"你按下了否按钮", L"消息", MB_OK);
break;
case BUTTON_CANCEL:
MessageBoxW(hwnd, L"你按下了取消按钮", L"消息", MB_OK);
break;
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// 注册窗口类
WNDCLASSW wc = {0};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = L"MyWindowClass";
RegisterClassW(&wc);
// 创建窗口
HWND hwnd = CreateWindowW(L"MyWindowClass", L"Button Test", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 200,
NULL, NULL, hInstance, NULL);
// 显示窗口
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
这段代码中,当你按下不同的按钮,会弹出不同的提示信息。