As a C++ beginner learning C++ and DirectX at the same time, I was wondering if a more experienced C++ developer would be able to go over the code and tell me what is done incorrectly or something that you would change.
Window.h
#pragma once
#include <string>
#include <windows.h>
namespace Graphics {
class Window
{
private:
const char *m_Title;
int m_Width;
int m_Height;
HINSTANCE m_hInstance;
public:
Window(const char *title, int width, int height);
~Window();
bool Init();
bool CreateD3DWindow();
void Loop();
inline int GetWidth() { return m_Width; }
inline int GetHeight() { return m_Height; }
};
}
Window.cpp
#include "Window.h"
#include <iostream>
namespace Graphics {
// Forward declarations
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
Window::Window(const char *title, int width, int height)
: m_Title(title), m_Width(width), m_Height(height)
{
}
Window::~Window()
{
}
bool Window::Init()
{
if (!CreateD3DWindow())
{
return false;
}
return true;
}
void Window::Loop()
{
MSG msg;
ZeroMemory(&msg, sizeof(MSG));
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
// Render
}
}
}
bool Window::CreateD3DWindow()
{
HWND hWnd;
WNDCLASSEX wc;
m_hInstance = GetModuleHandle(NULL);
// Window styling and options
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = m_hInstance;
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hIconSm = wc.hIcon;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = m_Title;
wc.cbSize = sizeof(WNDCLASSEX);
if (!RegisterClassEx(&wc))
{
std::cout << "RegisterClassEx failed!" << std::endl;
return false;
}
hWnd = CreateWindowEx(
WS_EX_APPWINDOW,
m_Title,
m_Title,
WS_OVERLAPPEDWINDOW,
GetSystemMetrics(SM_CXSCREEN) / 2 - m_Width / 2,
GetSystemMetrics(SM_CYSCREEN) / 2 - m_Height / 2,
m_Width,
m_Height,
NULL,
NULL,
m_hInstance,
NULL
);
if (!hWnd)
{
std::cout << "Failed to create window" << std::endl;
PostQuitMessage(0);
return false;
}
ShowWindow(hWnd, SW_SHOW);
return true;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CLOSE:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
{
switch (wParam)
{
case VK_ESCAPE:
PostQuitMessage(0);
return 0;
}
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
};
return 0;
}
}
Init(),CreateD3DWindow()andLoop()should all be private and invoked from the construtor (so that it basically behaves likestd::thread), but I don't know enough about your situation to determine if that's right here or not. \$\endgroup\$InitInstance->Window::Init(). \$\endgroup\$