c++ - 将 lparam 作为指向类的指针发送,并在 WndProc() 中使用它

标签 c++ winapi wndproc

我有这个抽象代码: 我想在 CreateWindowEx() 中使用 lParam(最后一个参数)来保存指向在 main - SaveArr 开头声明的类的指针。然后,我想在函数 WndProc 中使用它。 一开始我做了一个全局数组,然后我可以在任何地方使用它,但就 c++ 而言,它并不是那么“聪明”,所以我试图对它进行一些升级。

class Samples
{
        int arr[ITERATIONS+1];
        int index;
        ...
}

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
        Samples * SaveArr;
        ...
    hWnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW,
                          ClsName,
                          WindowCaption,
                          WS_OVERLAPPEDWINDOW,
                          INITIAL_WIN_LOCAT_X,
                          INITIAL_WIN_LOCAT_Y,
                          WIN_WIDTH,
                          WIN_HIGHT,
                          NULL,
                          NULL,
                          hInstance,
                          NULL);    //here i want to pass SaveArr, so that i can use it in the WndProc(...) function

...
return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
   ...      //here i would like to use lParam as the class pointer, meaning using the 
              SaveArr declared in the main function.

}

}

最佳答案

在窗口中添加来电者信息:

m_window = CreateWindow(..., this);

与扩展的 CreateWindowEx 类似。

获取指向调用者的指针:

template< typename CallerT >
[[nodiscard]]
CallerT* WindowCaller(HWND window, UINT message, LPARAM lParam) noexcept
{
    if (message == WM_NCCREATE) [[unlikely]]
    {
        const auto caller = reinterpret_cast< CallerT* >(
                            reinterpret_cast< CREATESTRUCT* >(lParam)->lpCreateParams);

        // Change the user data of the window for subsequent messages.
        ::SetWindowLongPtr(window, GWLP_USERDATA,
                           reinterpret_cast< LONG_PTR >(caller));

        return caller;
    }
    else
    {
        // Retrieve the user data of the window.
        return reinterpret_cast< CallerT* >(
                    ::GetWindowLongPtr(window, GWLP_USERDATA));
    }
}

此方法需要在您的消息回调中调用。

关于c++ - 将 lparam 作为指向类的指针发送,并在 WndProc() 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7384823/

相关文章:

c++ - 容器复杂度

c++ - 退出应用程序前关闭线程

c++ - 在 native Windows 应用程序的资源中嵌入文本文件

c++ - winapi GetAsyncKeyState() 不按描述工作?

delphi - 正确重写 WndProc

c++ - 为什么需要多个shared_future对象来同步数据

类构造中的 C++ 内存泄漏

winapi - windows API函数在哪里定义的?

.net - 是否有 .NET 命名空间可以在其中找到 WIN32 API 消息相关的 #defines,例如 WM_COMMAND 等

delphi - Delphi 6 TWinControl 后代的 WndProc() 有时如何在主 VCL 线程之外执行?