Windows Forms、托管 DirectX 和 C++
这个项目通过一个示例展示了如何结合托管 C++、托管 DirectX 和 Windows Forms。

引言
本文介绍了一种非常简洁明了的方法,使用托管 DirectX、Windows Forms 和 C++(在本例中为托管 C++)进行 3D 渲染。该应用程序是一个简单的 3D 点查看器,点数据来自一个 DataGridView
,允许用户编辑和多行复制/粘贴。
2008 年 11 月的 DirectX SDK 下载包含了对 MC++ 开发的完全支持:所有 DirectX API 都已完全翻译为 MC++。这对于使用 C++ 语言并希望使用 .NET 功能和 DirectX 功能的人来说,具有重要的意义。
背景
本文假定读者具备使用 Microsoft Visual Studio 的一些知识,具备托管 C++ 的背景知识,并且了解 Windows Forms 的一些基本概念。
Using the Code
该项目使用 Visual Studio 2008 创建,您还需要安装 DirectX SDK November 2008。
请记住检查项目是否包含引用 Microsoft.DirectX
和 Microsoft.DirectX.Direct3D
(请参阅项目->属性->公共属性->框架和引用)。
以下代码是从示例程序中的 Render
例程中提取的一段代码。3D 点渲染的数据源是一个名为 points
的点数组(类型为 array<CustomVertex::PositionColored, 1>
)。在渲染点之前,需要按照以下方式设置查看参数
/// <summary>
/// Render the 3D points vector.
/// </summary>
//Clear the backbuffer and color
device->Clear(ClearFlags::Target | ClearFlags::ZBuffer,
System::Drawing::Color::Black, 1.0f, 0);
//Begin the scene
device->BeginScene();
// View definitions
Vector3 CameraPos(Bmaxx, Bmaxy, Bmaxz);
Vector3 Center((Bmaxx+Bminx)/2, (Bmaxy+Bminy)/2,(Bmaxz+Bminz)/2);
CameraPos = CameraPos + (CameraPos-Center);
// View
device->Transform->World =
Matrix::RotationZ(Environment::TickCount / 2500.0f); // a rotating world
device->Transform->Projection =
Matrix::OrthoLH(8.0f, 8.0f, 0.1f, 1000.0f); // field of view
device->Transform->View =
Matrix::LookAtLH(CameraPos,Center, Vector3(0.0f, 0.0f, 1.0f)); // point of view
//Lighting
device->RenderState->Lighting = false;
device->RenderState->ZBufferEnable = true;
// Point size
device->SetRenderState(Direct3D::RenderStates::PointSize, 2.0f);
// Rendering of scene objects
device->VertexFormat = CustomVertex::PositionColored::Format;
device->DrawUserPrimitives(PrimitiveType::PointList, points->Length, points);
//End the scene
device->EndScene();
device->Present();
使用以下简单过程从 DataGridView
中提取 points
数组的数据:
/// <summary>
/// Update points vector from dataGridView1.
/// </summary>
try // using try to control data conversion errors
{
// actualize points
for (i = 0; i < points->Length; i++)
{
points[i].X = (float)System::Convert::ToDouble(dataGridView1[0,i]->Value);
points[i].Y = (float)System::Convert::ToDouble(dataGridView1[1,i]->Value);
points[i].Z = (float)System::Convert::ToDouble(dataGridView1[2,i]->Value);
points[i].Color = System::Drawing::Color::Red.ToArgb();
}
}
catch ( Exception^ exp )
{
// Cell data format error
MessageBox::Show( "Cell data format error: Row("+ i +")," +
exp->Message, "Error", MessageBoxButtons::OK, MessageBoxIcon::Exclamation );
return;
}
关注点
- 混合 C++、DirectX 和 Windows Forms
历史
- 版本 1.0 2009-03-24