为什么在这个函数中使用LRESULT CALLBACK

Why LRESULT CALLBACK is used in this function?

本文关键字:LRESULT CALLBACK 函数 为什么      更新时间:2023-10-16

最近,我开始学习DX11,我试图在WinAPI中创建消息循环。我在教程中看到了一个以前没有见过的LRESULT CALLBACK函数。它在窗口过程函数中被调用。这里是WndProc函数和MessageHandler函数(我正在谈论的函数)。

指向:

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);
    }
}
}

我不明白的是,为什么我们将"LRESULT CALLBACK"部分添加到MessageHandler函数?我知道,我们必须将它添加到WndProc函数中,但我不明白创建一个新函数并添加调用约定的意义。如果我们不向MessageHandler函数添加任何调用约定会怎样?如果我们没有创建MessageHandler函数并将KEY_DOWN监听器写入到windowproc的switch-case语句中会怎么样?

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

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

关于CALLBACK (__stdcall):
从"Windows内部"调用的函数必须是stdcall,因为Windows开发人员决定编写/编译它调用stdcall函数的Windows。理论上,任何CC都可以使用,但是Windows和你的代码必须具有相同的CC。
如果你只在你自己的程序代码中使用它,你自己的函数就不需要它。

LRESULT(类似int/指针的东西)只是返回类型。
不写int(或类似的东西)的原因是LRESULT是一个具有一定长度的int,如果MS出于某种原因决定改变它,他们只需要改变LRESULT的定义,但不是每个函数都有LRESULT返回类型。