win32程序通过LPCREATESTRUCT中的lpCreateParams传递参数给窗口过程函数

时间:2021-07-09 16:58:46

win32窗口程序中如果需要给窗口过程函数传递自定义参数,可以通过LPCREATESTRUCT结构体中的lpCreateParams进行传递。

创建窗口实例函数:

m_hWnd = CreateWindowEx(WS_EX_APPWINDOW, "FxWinAPP", "FxWinAPP", WS_OVERLAPPEDWINDOW,
nPosX, nPosY, wndRect.right - wndRect.left, wndRect.bottom - wndRect.top, NULL, NULL, m_hInst, this); 其中:
HWND CreateWindowEx(
DWORD DdwExStyle, //窗口的扩展风格
LPCTSTR lpClassName, //指向注册类名的指针
LPCTSTR lpWindowName, //指向窗口名称的指针
DWORD dwStyle, //窗口风格
int x, //窗口的水平位置
int y, //窗口的垂直位置
int nWidth, //窗口的宽度
int nHeight, //窗口的高度
HWND hWndParent, //父窗口的句柄
HMENU hMenu, //菜单的句柄或是子窗口的标识符
HINSTANCE hInstance, //应用程序实例的句柄
LPVOID lpParam //指向窗口的创建数据
);

在窗口过程函数的返回参数lParam指向LPCREATESTRUCT结构体指针,获取其中的了lpCreateParams:

LRESULT CALLBACK Win32Application::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc; if(message == WM_CREATE)
{
LPCREATESTRUCT create_struct = reinterpret_cast<LPCREATESTRUCT>(lParam);
void * lpCreateParam = create_struct->lpCreateParams;
Win32Application * this_window = reinterpret_cast<Win32Application *>(lpCreateParam);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this_window));
return DefWindowProc(hwnd, message, wParam, lParam);
}
Win32Application* pWin = reinterpret_cast<Win32Application *>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
if(!pWin || !pWin->m_pRenderWindow )
return DefWindowProc(hwnd, message, wParam, lParam);
RenderWindow* pRenderWnd = pWin->m_pRenderWindow;
switch (message)
{
case WM_COMMAND:
{
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
switch (wmId)
{
case :
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
break;
default:
return DefWindowProc(hwnd, message, wParam, lParam);
}
return ;
}

可以参考:http://members.gamedev.net/sicrane/articles/WindowClass.html  这篇文章主要讲如何在win32窗口程序中 将窗口过程函数定义为窗口类的成员函数,而不是通常我们所写的静态函数。

贴下主要代码:

class MyWindowClass {
public:
void WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK InitialWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
if (Msg == WM_NCCREATE) {
LPCREATESTRUCT create_struct = reinterpret_cast<LPCREATESTRUCT>(lParam);
void * lpCreateParam = create_struct->lpCreateParams;
MyWindowClass * this_window = reinterpret_cast<MyWindowClass *>(lpCreateParam);
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this_window));
SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&MyWindowClass::StaticWndProc));
return this_window->WndProc(hWnd, Msg, wParam, lParam);
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
} static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
LONG_PTR user_data = GetWindowLongPtr(hWnd, GWLP_USERDATA);
MyWindowClass * this_window = reinterpret_cast<MyWindowClass *>(user_data);
return this_window->WndProc(hWnd, Msg, wParam, lParam);
}
};