Click here to Skip to main content
15,886,199 members
Articles / Desktop Programming / Windows Forms

Easy Rendering with XNA Inside a Windows Form

Rate me:
Please Sign up or sign in to vote.
4.90/5 (17 votes)
16 Nov 2007CPOL4 min read 118.5K   7.4K   55  
This article shows an easy way to render 2D or 3D graphics in a Windows Form using XNA, keeping all the Windows features and controls
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XNA = Microsoft.Xna.Framework;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace XNAWinForms
{
    /// <summary>
    /// Windows form that inherits from XNAWinForms and adds the rendering of a simple rotating triangle
    /// 
    /// Author: Iñaki Ayucar (http://graphicdna.blogspot.com)
    /// Date: 14/11/2007
    /// 
    /// This software is distributed "for free" for any non-commercial usage. The software is provided “as-is.” 
    /// You bear the risk of using it. The contributors give no express warranties, guarantees or conditions.
    /// </summary>
    public partial class Form1 : XNAWinForm
    {
        private float mRotation = 0f;
        private Matrix mViewMat, mWorldMat, mProjectionMat;
        private BasicEffect mSimpleEffect;        

        VertexPositionColor[] triVerts = new VertexPositionColor[] {
            new VertexPositionColor(Vector3.Zero*2,
                        Microsoft.Xna.Framework.Graphics.Color.Blue),
            new VertexPositionColor(Vector3.Right*2,
                        Microsoft.Xna.Framework.Graphics.Color.Green),
            new VertexPositionColor(Vector3.Up*2,
                        Microsoft.Xna.Framework.Graphics.Color.Red)};


        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();

            this.DeviceResetting += new XNAWinForm.EmptyEventHandler(mWinForm_DeviceResetting);
            this.DeviceReset += new XNAWinForm.GraphicsDeviceDelegate(mWinForm_DeviceReset);
            this.OnFrameRender += new XNAWinForm.GraphicsDeviceDelegate(mWinForm_OnFrameRender);
            this.OnFrameMove += new GraphicsDeviceDelegate(Form1_OnFrameMove);

            mViewMat = mWorldMat = mProjectionMat = Matrix.Identity;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pDevice"></param>
        void Form1_OnFrameMove(Microsoft.Xna.Framework.Graphics.GraphicsDevice pDevice)
        {
            mRotation += 0.1f;
            this.mWorldMat = Matrix.CreateRotationY(mRotation);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pDevice"></param>
        void mWinForm_OnFrameRender(GraphicsDevice pDevice)
        {
            // Configure effect
            mSimpleEffect.World = this.mWorldMat;
            mSimpleEffect.View = this.mViewMat;
            mSimpleEffect.Projection = this.mProjectionMat;
            mSimpleEffect.DiffuseColor = XNA.Graphics.Color.DarkRed.ToVector3();
            mSimpleEffect.CommitChanges();


            // Draw
            mSimpleEffect.Begin();
            mSimpleEffect.Techniques[0].Passes[0].Begin();
            pDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleList,
                triVerts, 0, 1);
            mSimpleEffect.Techniques[0].Passes[0].End();
            mSimpleEffect.End();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pDevice"></param>
        void mWinForm_DeviceReset(GraphicsDevice pDevice)
        {
            // Re-Create effect
            mSimpleEffect = new BasicEffect(pDevice, null);

            // Configure device
            pDevice.VertexDeclaration = new VertexDeclaration(pDevice, VertexPositionColor.VertexElements);
            pDevice.RenderState.CullMode = CullMode.None;

            // Create camera and projection matrix
            mWorldMat = Matrix.Identity;
            mViewMat = Matrix.CreateLookAt(Vector3.Backward * 10,Vector3.Zero, Vector3.Up);
            mProjectionMat = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi / 4.0f,
                    (float)pDevice.PresentationParameters.BackBufferWidth / (float)pDevice.PresentationParameters.BackBufferHeight,
                    1.0f, 100.0f);
        }
        /// <summary>
        /// 
        /// </summary>
        void mWinForm_DeviceResetting()
        {
            // Dispose all
            if (mSimpleEffect != null)
                mSimpleEffect.Dispose();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Spain Spain
Inaki Ayucar is a Microsoft MVP in DirectX/XNA, and a software engineer involved in development since his first Spectrum 48k, in the year 1987. He is the founder and chief developer of The Simax Project (www.simaxvirt.com) and is very interested in DirectX/XNA, physics, game development, simulation, C++ and C#.

His blog is: http://graphicdna.blogspot.com

To contact Inaki: iayucar@simax.es

Comments and Discussions