我有这个抽象代码: 我想在 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/