我怎样才能使WinProc可以访问用它创建的对象? [英] How can I have WinProc have access to objects created out of it?
问题描述
在某个时候,我有这个
LRESULT CALLBACK WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if(msg==WM_CREATE)
{
LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
D2DResources* pD2DResources = (D2DResources*)pcs->lpCreateParams;
::SetWindowLongPtrW(
hWnd,
GWLP_USERDATA,
PtrToUlong(pD2DResources)
);
}
else
{
D2DResources* pD2DResources = reinterpret_cast<D2DResources*>(static_cast<LONG_PTR>(
::GetWindowLongPtrW(
hWnd,
GWLP_USERDATA
)));
switch(msg)
{
case WM_PAINT:
{
pD2DResources->OnRender();
ValidateRect(hWnd, NULL);
}
break;
case WM_SIZE:
{
UINT width = LOWORD(lParam);
UINT height = HIWORD(lParam);
pD2DResources->OnResize(width, height);
}
break;
因此,我的WinProc可以访问以前创建的D2DResources.现在,我希望它可以访问另一个先前创建的对象.我怎么做?我的意思是,它可以访问多个以前创建的对象吗?如果可以,怎么办?
So my WinProc has access to a previously created D2DResources. Now I want it to have access to another previously created object. How do I do that? I mean, can it have access to more than one previously created object? If so, how?
Raymond Chen说:将指针作为lpCreateParams传递到结构.您可以在结构中放入任何所需的内容.我怎么做?有人可以给我一个例子吗?
Raymond Chen said: "Pass a pointer to a structure as the lpCreateParams. You can put anything you want in the structure." How do I do that? Can anyone give me an exemple?
推荐答案
创建您自己的结构,并在创建它时将其传递给窗口.您可以在其中放置任何您喜欢的东西,包括指向其他东西的指针.
Create your own structure and pass it to the window when you create it. You can put anything you like in there, including pointers to other things.
例如
struct MyWindowData
{
D2DResources* pD2DResources;
void* pMyOtherData;
int iSomethingElse;
};
// on window creation
MyWindowData* pData = new MyWindowData(...);
HWND hWnd = CreateWindowEx(..., pData); // window will own the data and destroy it itself
// in the window procedure
if (msg == WM_CREATE)
{
MyWindowData* pData = ((LPCREATESTRUCT)lParam)->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (ULONG_PTR)pData);
}
else
{
MyWindowData* pData = (MyWindowData*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
switch (msg)
{
case WM_PAINT:
pData->pD2DResources->OnRender();
break;
case WM_NCDESTROY:
delete pData; // delete data on destroy
break;
}
...
}
这篇关于我怎样才能使WinProc可以访问用它创建的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!