Program.cs
using (Form1 frm = new Form1()) { if (!frm.InitializeGraphics()) { MessageBox.Show("error"); return; } frm.Show(); while (frm.Created) { frm.Render(); Application.DoEvents(); } }
Form1.cs
public partial class Form1 : Form { private Device device = null; private bool pause = false; public Form1() { InitializeComponent(); } public bool InitializeGraphics() //设置Device参数; { try { PresentParameters presentParams = new PresentParameters(); presentParams.Windowed = true; presentParams.SwapEffect = SwapEffect.Discard; presentParams.EnableAutoDepthStencil = true; presentParams.AutoDepthStencilFormat = DepthFormat.D16; //深度缓存区单元为16位二进制数; this.device = new Device( 0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams); this.device.DeviceReset += new System.EventHandler(this.OnResetDevice); this.OnCreateDevice(this.device, null); this.OnResetDevice(this.device, null); } catch (DirectXException) { return false; } return true; } public void OnCreateDevice(object sender, EventArgs e) { /* * 其他Device初始化工作; */ } public void OnResetDevice(object sender, EventArgs e) { /* * Device参数变化时调用; */ } public void Render() { if (this.device == null) return; if (this.pause) //当窗口最小化或者不是可视化时,停止渲染; return; this.device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.WhiteSmoke, 1.0f, 0); this.device.BeginScene(); /* * 渲染代码必须放在这里; */ this.device.EndScene(); this.device.Present(); } private void Form1_Paint(object sender, PaintEventArgs e) { this.Render(); } private void Form1_Resize(object sender, EventArgs e) { this.pause = (this.WindowState == FormWindowState.Minimized) || !this.Visible; } }