开发环境
VS2005
编译可能出现的问题:
字符集错误会提示类是问题。
错误 1 error C2440: 'initializing' : cannot convert from 'const char [13]' to 'LPCWSTR' e:\Documents\Visual Studio 2005\Projects\CreateDevice\CreateDevice\CreateDevice.cpp 33
在工程属性对话框常规页面中设置字符集为:
使用多字节字符集
选择[未设置]也没问题。
在没有添加d3d9.lib 库前编译会报下面的错误
错误 1 error LNK2028: 无法解析的标记(0A00001D) "extern "C" struct IDirect3D9 * __stdcall Direct3DCreate9(unsigned int)" (?Direct3DCreate9@@$$J14YGPAUIDirect3D9@@I@Z),该标记在函数 "long __cdecl InitD3D(struct HWND__ *)" (?InitD3D@@$$FYAJPAUHWND__@@@Z) 中被引用 CreateDevice.obj
附加依赖库添加方法有2种。
1、直接在程序中使用宏调用 #pragma comment(lib,"d3d9.lib")
2、在工程属性对话框内的连接器->输入页面中添加依赖项"d3d9.lib"
全部代码
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
//-----------------------------------------------------------------------------
// 名称: CreateDevice.cpp
//
// 功能: 这个文件创建了一个Direct3D对象和一个Direct3D设备,并使用一个窗口作为
// 渲染目标表面。
//
//-----------------------------------------------------------------------------
// 包含Direct3D头文件
#include <d3d9.h>
#pragma comment(lib,"d3d9.lib")
LPDIRECT3D9 g_pD3D = NULL;
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
HRESULT InitD3D(HWND hWnd);
VOID Cleanup();
VOID Render();
LRESULT WINAPI MsgProc(HWND, UINT, WPARAM, LPARAM);
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, INT)
{
/// 注册窗口类
WNDCLASSEX wc = {sizeof(WNDCLASSEX),
CS_CLASSDC,
MsgProc,
0L,
0L,
GetModuleHandle(NULL),
NULL, NULL, NULL, NULL,
"D3D Tutorial",
NULL};
RegisterClassEx(&wc);
HWND hWnd = CreateWindow("D3D Tutorial", "D3D Tutorial 01: CreateDevice",
WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
GetDesktopWindow(), NULL, wc.hInstance, NULL);
/// 创建窗口
if (SUCCEEDED(InitD3D(hWnd)))
{
/// 显示窗口
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
/// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
//删除注册的类
UnregisterClass("D3D Tutorial", wc.hInstance);
return 0;
}
HRESULT InitD3D(HWND hWnd)
{
if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
return E_FAIL;
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
if (FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice)))
return E_FAIL;
return S_OK;
}
VOID Render()
{
if (NULL == g_pd3dDevice)
return;
g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0, 255), 1.0f, 0);
if (SUCCEEDED(g_pd3dDevice->BeginScene()))
{
g_pd3dDevice->EndScene();
}
g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
}
VOID Cleanup()
{
if (g_pd3dDevice != NULL)
g_pd3dDevice->Release();
if (g_pD3D != NULL)
g_pD3D->Release();
}
LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
Cleanup();
PostQuitMessage(0);
return 0;
case WM_PAINT:
Render();
ValidateRect(hWnd, NULL);
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}