在开始使用 DirectX 编程前,需要先创建一个 Windows 窗口,供 DirectX 使用。在创建窗口前,为了熟悉 Windows 编程,先写一个 Hello world 程序看看:
  | 
  | 
WINAPI 的作用是颠倒传入的参数的顺序。一般函数的参数从右到左传入,而带有 WINAPI 的函数,参数从左到右传入。
WinMain 是 Windows 程序的入口,相当于 Win32 console 程序的 main。4 个形参的具体说明详见《DirectX 11 编程:常用 Windows API》。
MessageBox 函数用于创建一个 MessageBox。
上面的代码运行会显示:

接下来可以把 MessageBox 替换为 Windows 窗口了。
创建窗口需要三步:
- 注册窗口
 - 创建窗口
 - 显示窗口
 
所以 WinMain 的基本结构是:
  | 
  | 
接下来分别定义 registerWindow、createWindow 和 showWindow。
registerWindow
注册窗口类(window class)时,需要调用 Windows 的 RegisterClassEx 函数,详见《DirectX 11 编程:常用 Windows API》。
在调用 RegisterClassEx 前,先填充好 WNDCLASSEX 结构体的字段:
  | 
  | 
WindowProc 是我们自定义的函数,用于窗口处理 Windows 消息(如鼠标点击、拖动、缩放大小),代码如下:
  | 
  | 
然后就可以调用 RegisterClassEx 函数了:
RegisterClassEx(&wc);
createWindow
创建窗口,需要调用 Windows 的 CreateWindowEx 函数,详见《DirectX 11 编程:常用 Windows API》。
代码如下:
RECT wr = { 0, 0, 500, 400 };  // left, top, right, bottom
AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE);          // adjust the size, client size is 500 * 400
// the handle for the window, filled by a function
HWND hWnd = CreateWindowEx(NULL,
                           L"WindowClass1",                 // name of the window class
                           L"Our First Windowed Program",   // title of the window
                           WS_OVERLAPPEDWINDOW,             // window style
                           300,                             // x-position of the window
                           300,                             // y-position of the window
                           wr.right - wr.left,              // width of the window
                           wr.bottom - wr.top,              // height of the window
                           NULL,                            // we have no parent window, NULL
                           NULL,                            // we aren't using menus, NULL
                           hInstance,                       // application handle
                           NULL);                           // used with multiple windows, NULL
AdjustWindowRect 函数根据参数给出的“窗口内的矩形大小”(即除去窗口边框的矩形,下图的 Client Size),计算窗口(包括边框)的实际大小(下图的 Window Size),详见《DirectX 11 编程:常用 Windows API》。

showWindow
showWindow 只需要调用
ShowWindow(HWND, int)
即可,ShowWindow(HWND, int) 用法详见《DirectX 11 编程:常用 Windows API》。
把创建窗口的三步整合,得到以下代码:
  | 
  | 
运行后显示:
