最近,我开始学习DX11,并试图在WinAPI中创建消息循环。我从之前从未见过的教程中看到了LRESULT CALLBACK函数。在“窗口过程”函数中调用它。这是WndProc函数和MessageHandler函数(我正在谈论的函数)。

WndProc:

LRESULT CALLBACK WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)
{
switch(umessage)
{
    // Check if the window is being destroyed.
    case WM_DESTROY:
    {
        PostQuitMessage(0);
        return 0;
    }

    // Check if the window is being closed.
    case WM_CLOSE:
    {
        PostQuitMessage(0);
        return 0;
    }

    // All other messages pass to the message handler in the system class.
    default:
    {
        return ApplicationHandle->MessageHandler(hwnd, umessage, wparam, lparam);
    }
}
}

MessageHandler:
LRESULT CALLBACK SystemClass::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
switch(umsg)
{
    // Check if a key has been pressed on the keyboard.
    case WM_KEYDOWN:
    {
        // If a key is pressed send it to the input object so it can record that state.
        m_Input->KeyDown((unsigned int)wparam);
        return 0;
    }

    // Check if a key has been released on the keyboard.
    case WM_KEYUP:
    {
        // If a key is released then send it to the input object so it can unset the state for that key.
        m_Input->KeyUp((unsigned int)wparam);
        return 0;
    }

    // Any other messages send to the default message handler as our application won't make use of them.
    default:
    {
        return DefWindowProc(hwnd, umsg, wparam, lparam);
    }
}
}

我不明白的是,为什么我们要在MessageHandler函数中添加“LRESULT CALLBACK”部分?我知道,我们必须将其添加到WndProc函数中,但是我不了解创建一个新函数并将其添加为调用约定的意义。如果我们不向MessageHandler函数添加任何调用约定怎么办?如果我们不创建MessageHandler函数,而是将KEY_DOWN侦听器写入WndProc的switch-case语句,该怎么办?

这些代码在一个类中,ApplicationHandler指针指向“this”。

最佳答案

没有明显的理由将SystemClass::MessageHandler声明为CALLBACK,因为它不是static,因此不能用作Windows的消息处理程序。在显示的代码中没有理由将SystemClass::MessageHandler声明为CALLBACK

10-08 15:52