C# Managed DirectX 程序基本框架

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;
        }
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值