2 yangkunqiankun yangkunqiankun 于 2016.04.26 01:22 提问

Windows程序设计产生的消息问题 2C

程序源码如下:
#include
#pragma comment(lib,"WINMM.LIB")
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("Hello world!");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;

wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_HAND);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass (&wndclass))
{
    MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR);
    return 0;
}
hwnd = CreateWindow(szAppName,
    TEXT("The Hello Program"),
    WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT,
    CW_USEDEFAULT,
    CW_USEDEFAULT,
    CW_USEDEFAULT,
    NULL,
    NULL,
    hInstance,
    NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&msg, NULL, 0, 0))
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
return msg.wParam;

}

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
switch (message)
{
case WM_CREATE:
PlaySound(TEXT ("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC);
return 0;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
PlaySound(TEXT("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC);
DrawText(hdc, TEXT("Hello, Windows 98!"), -1, &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}

为了能够清楚程序运行机制,采取单步调试,发现在执行CreateWindow()之后,程序跳转到switch(message),接着跳转到return DefWindowProc(hwnd, message, wParam, lParam);这一句,想问一下CreateWindow()这一句不是只产生WM_CREATE这个消息,而是会产生一些其他程序中不关心的消息之后才有WM_CREATE这个消息入队列?不然为什么没有直接执行case,而是执行了默认的消息处理函数?

2个回答

caozhy
caozhy   Ds   Rxr 2016.04.26 04:49

https://msdn.microsoft.com/en-us/library/windows/desktop/ms632619(v=vs.85).aspx

说的很清楚

(The message is sent before the function returns.)

你说执行完CreateWindow()之后,那么这个消息早处理过了。

lboych
lboych   2016.05.02 09:50

消息进入队列,等待处理。在你想要的地方直接下断点就好了

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!