我正在创建一个Windows应用程序。我正在尝试设置一个 Application 类并处理其中的成员函数中的事件,并预先声明该类的一个实例以在 Windows 过程中调用。
我希望看到一个白色的无响应窗口,但窗口创建返回 nullptr。这是main.cpp
#include <windows.h>
#include "WinApplication.h"
WinApplication* app;
LRESULT CALLBACK windowCallback(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//return DefWindowProc(hwnd, uMsg, wParam, lParam);
return app->appCallback(uMsg, wParam, lParam);
}
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
app = new WinApplication();
WNDCLASS window_class = {};
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.lpszClassName = TEXT("Window Class");
window_class.lpfnWndProc = windowCallback;
// Register Class
if (!RegisterClass(&window_class))
return 1;
// Create Window
HWND window = CreateWindow(window_class.lpszClassName, TEXT("MyApp"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, DEF_WIDTH, DEF_HEIGHT, 0, 0, hInstance, 0);
app->init(window);
while (true) { }
return 0;
}
这是会员回调:
LRESULT WinApplication::appCallback(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return 0;
}
如有任何帮助,我们将不胜感激
您不能 directoy 将类函数传递给 WinAPI 回调。
大多数调用回调的 WinAPI 函数也采用一个参数,您可以使用该参数来引用您的类。
很久以前我写了这个例子(在https://cplusplus.com/forum/general/170775/#msg851518),它演示了该技术:
#include <iostream>
#include <string>
#include <vector>
#ifndef NOMINMAX
#define NOMINMAX
#endif
extern "C"
{
#include <windows.h>
}
//----------------------------------------------------------------------------
// EnumWindows() -- return a list of toplevel window handles
class EnumerateWindows: public std::vector <HWND>
{
private:
// Here's the class's callback method ......................................
BOOL EnumWindowsMethod( HWND hWnd )
{
push_back( hWnd );
return TRUE;
}
// Here's the static callback procedure ....................................
static BOOL CALLBACK EnumWindowsProc( HWND hWnd, LPARAM lParam )
{
return reinterpret_cast <EnumerateWindows*> (lParam)->EnumWindowsMethod( hWnd );
}
public:
// Here's the function that makes it all happen ............................
EnumerateWindows()
{
EnumWindows( EnumWindowsProc, (LPARAM)this );
}
};
//----------------------------------------------------------------------------
// GetWindowText() -- return a window's titlebar text
std::string GetWindowText( HWND hWnd )
{
std::string s( MAX_PATH, '\0' );
s.resize( GetWindowText( hWnd, const_cast <char*> (s.c_str()), MAX_PATH ) );
return s;
}
//----------------------------------------------------------------------------
int main()
{
std::cout << "Toplevel windows (that actually have titles) are:\n";
for (const auto& handle : EnumerateWindows())
{
const std::string& title = GetWindowText( handle );
if (!title.empty())
std::cout << " \"" << title << "\"\n";
}
}