我尝试通过本教程开始 c# directX 编程: http://www.riemers.net/eng/Tutorials/DirectX/Csharp/Series1/tut2.php 我使用的是Visual Studion Community 2015,我的代码是这样的:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace DirecxTest01
{
public partial class Form1 : Form
{
private Device device;
public Form1()
{
InitializeComponent();
InitializeDevice();
}
private void InitializeDevice()
{
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
device.Clear(ClearFlags.Target, Color.DarkSlateBlue, 1.0f, 0);
device.Present();
}
}
}
我还添加了对所有 DirectX dll 的引用。当我运行该程序时,没有任何反应,甚至没有出现表单窗口。没有错误消息,只是什么都没有。我尝试逐行注释掉 DirectX 内容。即使使用此代码,程序也会挂起:
private void InitializeDevice()
{
PresentParameters presentParams = new PresentParameters();
//presentParams.Windowed = true;
//presentParams.SwapEffect = SwapEffect.Discard;
//device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
}
当我发表评论时
//PresentParameters presentParams = new PresentParameters();
到,至少 Windowas Form 出现了。
我的代码有什么问题吗?
您使用的教程适用于已弃用的 Managed DirectX 1.1 程序集。它们是为 .NET 1.1 编写的,与 .NET 4.0 或更高版本不兼容——尽管有一些 hack 试图让它们工作。
/platform:anycpu
)使用它们。您必须使用 /platform:x86
进行构建,并保持在 32 位应用程序 2 GB 内存空间的限制内。简而言之: 不要使用它们。使用更现代的东西,如 SharpDX、SlimDX 或 Unity3D。
我知道这是一个旧线程,但我遇到了确切的问题,并且“不使用 DirectX”的解决方案不是一个选项,因为我正在现有系统上工作,没有使用 DirectX 升级所有相关部分的选项dll。
幸运的是,我找到了一个在 .NET Framework 版本 4.6.1 上使用旧 DirectX 程序集的解决方案。
只需将其添加到 App.config 文件中(位于
</appSettings>
正下方):
<startup useLegacyV2RuntimeActivationPolicy="true" >
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.61"/>
</startup>
似乎有一个库延续了SharpDX的方式,这就是Vortice.Windows。
Vortice.Windows 是 Win32 和 UWP 库的集合,具有对 DXGI、WIC、DirectWrite、Direct2D、Direct3D9、Direct3D11、Direct3D12、XInput、XAudio2、X3DAudio、DirectInput、DirectStorage、DirectML、UIAnimation 和 DirectSound 的绑定支持。
此库面向 .net7.0 和 .net8.0 并使用现代 C# 12,请参阅 CHANGELOG 以获取提交之间的更改列表。