MFC和Direct3D9一起使用

时间:2024-09-05 10:36:02

第一步:新建MFC单文档项目,向导如下:

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

第二步:添加引用,在项目属性的VC++目录中修改Include和lib文件夹。

MFC和Direct3D9一起使用

MFC和Direct3D9一起使用

第三步:在stdafx.h文件Include部分的最后添加如下引用。

#include "d3d9.h"
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")

第四步:在视图类头文件中添加如下代码:

     LPDIRECT3D9             g_pD3D     ; //Direct3D对象
LPDIRECT3DDEVICE9 g_pd3dDevice; //Direct3D设备对象
HRESULT InitD3D( HWND hWnd );
VOID Render();

第五步:在实现文件中添加如下代码。

构造函数中添加:

 g_pD3D       = NULL; //Direct3D对象
g_pd3dDevice = NULL; //Direct3D设备对象

实现InitD3D(HWND hWnd):

 HRESULT CDirect3DFirstView:: InitD3D( HWND hWnd )
{
//创建Direct3D对象, 该对象用来创建Direct3D设备对象
if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
return E_FAIL; //设置D3DPRESENT_PARAMETERS结构, 准备创建Direct3D设备对象
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; //创建Direct3D设备对象
if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp, &g_pd3dDevice ) ) )
{
return E_FAIL;
} return S_OK;
}

实现Render():

 VOID CDirect3DFirstView:: Render()
{
//清空后台缓冲区
g_pd3dDevice->Clear( , NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(, , ), 1.0f, ); //开始在后台缓冲区绘制图形
if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
{
//在此在后台缓冲区绘制图形 //结束在后台缓冲区渲染图形
g_pd3dDevice->EndScene();
} //将在后台缓冲区绘制的图形提交到前台缓冲区显示
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}

Render

OnDraw中的代码:

 void CDirect3DFirstView::OnDraw(CDC* /*pDC*/)
{
CDirect3DFirstDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
if (g_pD3D==NULL)
{
if( SUCCEEDED( InitD3D( this->m_hWnd ) ) )
{
Render();
}
else
{
AfxMessageBox(L"error");
}
}
else
{
Render();
} // TODO: 在此处为本机数据添加绘制代码
}

OnDraw

第六步:编译运行,结果如下:

MFC和Direct3D9一起使用