在上一个教程里面我们已经搭好了环境,不过还什么都没有,这个教程我们将创建一个窗口。

1、stdafx.h
#pragma once

#include <windows.h>
#include <d3d12.h>
#include <dxgi1_4.h>
#include <D3Dcompiler.h>
#include <DirectXMath.h>
#include "d3dx12.h"

// 窗口句柄
HWND hwnd = NULL;

// 窗口名字
LPCTSTR WindowName = L"yangshuohao";

// 窗口标题
LPCTSTR WindowTitle = L"Window";

//窗口宽和高
int Width = 800;
int Height = 600;

// 是否为全屏
bool FullScreen = false;

// 创建一个窗口
bool InitializeWindow(HINSTANCE hInstance,
	int ShowWnd,
	int width, int height,
	bool fullscreen);

// 主循环
void mainloop();

// 窗口消息的回调函数
LRESULT CALLBACK WndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam);
2、Main.cpp
#include "stdafx.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
	// 创建窗口
	if (!InitializeWindow(hInstance, nShowCmd, Width, Height, FullScreen))
	{
		MessageBox(0, L"窗口初始化失败",L"提示框", MB_OK);
		return 0;
	}

	// 开始主循环
	mainloop();

	return 0;
}

bool InitializeWindow(HINSTANCE hInstance,int ShowWnd,int width, int height,bool fullscreen)
{
	//如果fullscreen=true全屏显示
	if (fullscreen)
	{
		HMONITOR hmon = MonitorFromWindow(hwnd,MONITOR_DEFAULTTONEAREST);
		MONITORINFO mi = { sizeof(mi) };
		GetMonitorInfo(hmon, &mi);

		width = mi.rcMonitor.right - mi.rcMonitor.left;
		height = mi.rcMonitor.bottom - mi.rcMonitor.top;
	}

	WNDCLASSEX wc;

	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = NULL;
	wc.cbWndExtra = NULL;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 2);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = WindowName;
	wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	if (!RegisterClassEx(&wc))
	{
		MessageBox(NULL, L"注册窗口失败",L"提示框", MB_OK | MB_ICONERROR);
		return false;
	}

	hwnd = CreateWindowEx(NULL,WindowName,WindowTitle,WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT,width, height,NULL,NULL,hInstance,NULL);

	if (!hwnd)
	{
		MessageBox(NULL, L"创建窗口失败",L"提示框", MB_OK | MB_ICONERROR);
		return false;
	}

	if (fullscreen)
	{
		SetWindowLong(hwnd, GWL_STYLE, 0);
	}

	ShowWindow(hwnd, ShowWnd);
	UpdateWindow(hwnd);

	return true;
}

void mainloop() {
	MSG msg;
	ZeroMemory(&msg, sizeof(MSG));

	while (true)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
				break;

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else 
		{
			//运行游戏代码
		}
	}
}

//回调函数处理消息
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
	switch (msg)
	{
	case WM_KEYDOWN:
		if (wParam == VK_ESCAPE) 
		{
			if (MessageBox(0, L"你确定要退出吗?",L"提示框", MB_YESNO | MB_ICONQUESTION) == IDYES)
				DestroyWindow(hwnd);
		}
		return 0;

	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hwnd,msg,wParam,lParam);
}
3、按下F5运行,结果如下图。

创建一个窗口_DirectX

到这里我们就已经创建了一个窗口了,接下来就可以在这个窗口里面渲染东西啦。

创建一个窗口_窗口_02创建一个窗口_窗口_03创建一个窗口_DirectX_04