Allegro或SDL如何为Windows创建窗口以及如何自己完成?
我正在尝试为游戏编写WinApi包装器,但是当我看到基本的WinApi模板并想要将它包装成这样的东西时,我完全迷失了
init();
while()
{
update();
}
exit();
Run Code Online (Sandbox Code Playgroud)
他们用CreateWindowEx.一个非常简单的创建窗口的WinAPI应用程序看起来像这样:
#include <Windows.h>
// If you're using MSVC, this is the easiest HINSTANCE. Other compilers
// get it from WinMain and pass in to constructor.
extern "C" IMAGE_DOS_HEADER __ImageBase;
HINSTANCE hInstance = (HINSTANCE)&__ImageBase;
class Window {
HWND hWnd;
static LRESULT __stdcall WindowProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (Window* ptr = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)))
return ptr->DoMessage(hWnd, message, wParam, lParam);
else
return DefWindowProc(hWnd, message, wParam, lParam);
}
LRESULT DoMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch(msg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
public:
bool DoMessages() {
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
// Translate the message and dispatch it to WindowProc()
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (msg.message == WM_QUIT) {
return false;
}
return true;
}
Window() {
WNDCLASSEX wc;
// clear out the window class for use
ZeroMemory(&wc, sizeof(WNDCLASSEX));
// fill in the struct with the needed information
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = L"WindowClass1";
RegisterClassEx(&wc);
// create the window and use the result as the handle
hWnd = CreateWindowEx(NULL,
L"WindowClass1", // name of the window class
L"Wide::Development", // title of the window
WS_OVERLAPPEDWINDOW, // window style. Always windowed for now.
0, // x-position of the window
0, // y-position of the window
1, // width of the window
1, // height of the window
NULL, // we have no parent window, NULL
NULL, // we aren't using menus, NULL
hInstance, // application handle
NULL);
ShowWindow(hWnd, SW_MAXIMIZE); // Snap our window to the user's desktop res, minus taskbar etc.
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); // Make sure that our WindowLongPtr is updated.
}
};
int main() {
Window window;
while(window.DoMessages()) {
// Do app updates, or sleep() if you're mostly waiting on user input
Sleep(50);
}
// When DoMessages() returns false, the window was destroyed, so return.
}
Run Code Online (Sandbox Code Playgroud)
您可以查找MSDN文档以获取有关这些功能的更多信息.基本上,它所做的只是创建一个非常简单的最大化非全屏窗口,注册输入,当窗口被销毁时,退出应用程序.您会注意到我实际上已将输入转发给Window对象,因此这个最基本的框架都是面向对象的,如果您愿意,可以在这里使用继承,只是不要忘记WindowLongPtr函数使用void*而且不是类型安全的.
值得一提的是,对于像MSVC这样的编译器,如果你#include <Windows.h>,他们希望你使用WinMain入口点,而不是main().
游戏渲染和更新代码通常比WinAPI更复杂和困难,因此我会在DirectX9.0c或DirectX10上获取一本书.