Click here to Skip to main content
Click here to Skip to main content

MDX WinForm with .NET Controls

By , 25 May 2006
 

Introduction

This article shows how to use .NET Windows Form controls with managed DirectX content. Most books/tutorials use a WinForm strictly with MDX content. But people are more interested in using WinForm controls together with MDX. This question is frequently asked and not well answered. Here, I present a small project using .NET 2.0 and Visual Studio 2005.

Technique

The most important part of this project is the DirectX device creation. Normally it's:

device = new Device(0, DeviceType.Hardware, this, 
         CreateFlags.SoftwareVertexProcessing, presentParams);
'this' is the alias of 'Form' used to represent this winForm.

In order to make .NET controls such as menubar, etc. to co-exist with a DirectX control, I set up a panel to be used by DirectX.

private System.Windows.Forms.Panel panel1;
// Initialize panel1
device = new Device(0, DeviceType.Hardware, panel1, 
         CreateFlags.SoftwareVertexProcessing, presentParams);

To demonstrate that this works, I have provided a simple managed DirectX project with this project that can be downloaded. Here is the complete source code. Copy/paste and compile with .NET 2.0 managed DirectX.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace Chapter1Code
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private Device device = null;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;
        private Panel panel1;
        private MenuStrip menuStrip1;
        private ToolStripMenuItem mDXFormWithMenuToolStripMenuItem;
        private ToolStripMenuItem exitToolStripMenuItem;
        private float angle = 0.0f;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            this.Size = new Size(800, 600);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint | 
                          ControlStyles.Opaque, true);
        }

        /// <summary>
        /// We will initialize our graphics device here
        /// </summary>
        public void InitializeGraphics()
        {
            // Set our presentation parameters
            PresentParameters presentParams = new PresentParameters();

            presentParams.Windowed = true;
            presentParams.SwapEffect = SwapEffect.Discard;

            // Create our device
            device = new Device(0, DeviceType.Hardware, panel1, 
                     CreateFlags.SoftwareVertexProcessing, 
                     presentParams);            
        }

        private void SetupCamera()
        {            
            device.RenderState.CullMode = Cull.None;
            device.Transform.World = Matrix.RotationAxis(new Vector3(angle / 
                                     ((float)Math.PI * 2.0f), 
                                     angle / ((float)Math.PI * 4.0f), 
                                     angle / ((float)Math.PI * 6.0f)), 
                                     angle / (float)Math.PI);
            angle += 0.1f;

            device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, 
                                          this.Width / this.Height, 1.0f, 100.0f);
            device.Transform.View = Matrix.LookAtLH(new Vector3(0,0, 5.0f), 
                                    new Vector3(), new Vector3(0,1,0));
            device.RenderState.Lighting = true;
        }

        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {            
            device.Clear(ClearFlags.Target, 
                System.Drawing.Color.CornflowerBlue, 1.0f, 0);

            SetupCamera();

            CustomVertex.PositionNormalColored[] verts = 
                  new CustomVertex.PositionNormalColored[3];
            verts[0].Position = new Vector3(0.0f, 1.0f, 1.0f);
            verts[0].Normal = new Vector3(0.0f, 0.0f, -1.0f);
            verts[0].Color = System.Drawing.Color.White.ToArgb();
            verts[1].Position = new Vector3(-1.0f, -1.0f, 1.0f);
            verts[1].Normal = new Vector3(0.0f, 0.0f, -1.0f);
            verts[1].Color = System.Drawing.Color.White.ToArgb();
            verts[2].Position = new Vector3(1.0f, -1.0f, 1.0f);
            verts[2].Normal = new Vector3(0.0f, 0.0f, -1.0f);
            verts[2].Color = System.Drawing.Color.White.ToArgb();

            device.Lights[0].Type = LightType.Point;
            device.Lights[0].Position = new Vector3();
            device.Lights[0].Diffuse = System.Drawing.Color.White;
            device.Lights[0].Attenuation0 = 0.2f;
            device.Lights[0].Range = 10000.0f;
            
            device.Lights[0].Enabled = true;

            device.BeginScene();
            device.VertexFormat = CustomVertex.PositionNormalColored.Format;
            device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, verts);
            device.EndScene();

            device.Present();

            this.Invalidate();
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.panel1 = new System.Windows.Forms.Panel();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.mDXFormWithMenuToolStripMenuItem = 
                 new System.Windows.Forms.ToolStripMenuItem();
            this.exitToolStripMenuItem = 
                 new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // panel1
            // 
            this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.panel1.Location = new System.Drawing.Point(0, 24);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(307, 275);
            this.panel1.TabIndex = 0;
            // 
            // menuStrip1
            // 
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.mDXFormWithMenuToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(307, 24);
            this.menuStrip1.TabIndex = 1;
            this.menuStrip1.Text = "menuStrip1";
            // 
            // mDXFormWithMenuToolStripMenuItem
            // 
            this.mDXFormWithMenuToolStripMenuItem.DropDownItems.AddRange(
                               new System.Windows.Forms.ToolStripItem[] {
            this.exitToolStripMenuItem});
            this.mDXFormWithMenuToolStripMenuItem.Name = 
                 "mDXFormWithMenuToolStripMenuItem";
            this.mDXFormWithMenuToolStripMenuItem.Size = 
                 new System.Drawing.Size(117, 20);
            this.mDXFormWithMenuToolStripMenuItem.Text = "MDX form with Menu";
            // 
            // exitToolStripMenuItem
            // 
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
            this.exitToolStripMenuItem.Text = "Exit";
            this.exitToolStripMenuItem.Click += 
                 new System.EventHandler(this.exitToolStripMenuItem_Click);
            // 
            // Form1
            // 
            this.ClientSize = new System.Drawing.Size(307, 299);
            this.Controls.Add(this.panel1);
            this.Controls.Add(this.menuStrip1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main() 
        {
            using (Form1 frm = new Form1())
            {
                // Show our form and initialize our graphics engine
                frm.Show();
                frm.InitializeGraphics();
                Application.Run(frm);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}

History

  • 25th May, 2006: Initial post

License

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

About the Author

Fei Liu
Web Developer
United States United States
Member
I currently work and live in NJ, US. I am interested in C/C++/CLR/C# technologies. My blog is http://meditation-art.blogspot.com/

 

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberBattleDroid14 Apr '11 - 12:50 
One of a kind.
QuestionChange Array to List in MDXmemberled12327 Jan '10 - 3:42 
Creating a report in Team Foundation Server(TFS) and my parameter is set as an array and I want to be able to display this array. I want to be able to switch the array to a list and then be able to show what is selected out of the list by the parameter the user selects. Can someone help please?? Smile | :)
QuestionForm update issue?memberEskildh3 Nov '08 - 2:17 
Hello and thank you for providing a very useful tutorial.
 
I noticed that the menustrip on the form doesn’t repaint until moving or resizing the form.
 
When setting up a similar project with more windows components, they all have the same issue with not being repainted unless the window is moved or resized. I tried calling the base OnPaint event without any noticeable difference.
 
Any suggestions about this problem?
GeneralExcellent!memberwck5931 Jan '08 - 10:48 
Cut & Pasted into DevStudio 8. All I had to do was add references for the assemblies and it compiled and worked first time. Short, sweet and easy to understand.
 
Thanks!
GeneralJust what I needed!memberSrdjanP29 Nov '06 - 9:48 
Just wanted to thank you for the article, it's just what I was looking for!
 
Thanks!!!
QuestionWhat is MDX?memberJun Du26 May '06 - 4:22 
This is the list of findings you would get from searching "http://www.acronymfinder.com":
 
[more information and searches] **** MDX Mountain Dew X search Amazon.com
[more information and searches] **** MDX Miami-Dade Expressway Authority (Florida) search Amazon.com
[more information and searches] **** MDX Multi Dimensional Expression search Amazon.com
[more information and searches] **** MDX Modular Digital Exchange (Redcom Laboratories, Inc.) search Amazon.com
[more information and searches] **** MDX Modify Index (assembler language instruction) search Amazon.com
[more information and searches] *** MDX Multi-Channel Data Exchange search Amazon.com
[more information and searches] *** MDX Maintenance Diagnostic Extended search Amazon.com
 
Which one is your article discussing about?
 
- It's easier to make than to correct a mistake.

AnswerRe: What is MDX?staffNishant Sivakumar26 May '06 - 4:38 
Managed DirectX
 
Regards,
Nish
Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
Currently working on C++/CLI in Action for Manning Publications.

GeneralRe: What is MDX?staffNishant Sivakumar26 May '06 - 5:52 
Nishant Sivakumar wrote:
Score: 1.0 (1 vote).

 
Damn! What was 1-votable about my answer? Mad | :mad:
 

 
Regards,
Nish
Nish’s thoughts on MFC, C++/CLI and .NET (my blog)
Currently working on C++/CLI in Action for Manning Publications.

GeneralRe: What is MDX?memberFei Liu26 May '06 - 6:31 
Because people are never happy? hhehe..yes, MDX is the synonym of managed directx.
GeneralRe: What is MDX?memberJun Du27 May '06 - 10:51 
Oops, I guess it's me. I remember I voted 5.Confused | :confused: Maybe because of my browser (or something), as I use Linux machine at work. Anyway, I owe you a big 5. Really sorry about that.
 
- It's easier to make than to correct a mistake.
Generalfilesmemberpablleaf25 May '06 - 18:44 
where are the files?!?!
GeneralThis article shows how to...protectorMarc Clifton25 May '06 - 13:01 
No it doesn't. Care to rework it?
 
Marc
 
Pensieve
Some people believe what the bible says. Literally. At least [with Wikipedia] you have the chance to correct the wiki -- Jörgen Sigvardsson
GeneralRe: This article shows how to...memberFei Liu26 May '06 - 6:19 
It does work, but something isn't right with the download. I'll just post the complete source code later when I get home.
GeneralRe: This article shows how to...protectorMarc Clifton26 May '06 - 7:54 
The code might, but I'm refering to when you say, "this article shows...". The article doesn't show how at all.
 
Marc
 
Pensieve
Some people believe what the bible says. Literally. At least [with Wikipedia] you have the chance to correct the wiki -- Jörgen Sigvardsson
GeneralRe: This article shows how to...memberFei Liu26 May '06 - 15:50 
Ah? Did you read the article at all?Laugh | :laugh:
GeneralRe: This article shows how to...memberDanilo Corallo9 Jun '06 - 23:57 
Hi Fei Liu,
 
this article surely talks about a cool topic, but what Marc is saying is that you miss to explain how the code works, which functions are involved and what's the logic behind. For instance I would like to know how to start a new project with Managed DirectX (or what I need to compile yours).
 
Best Regards

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 25 May 2006
Article Copyright 2006 by Fei Liu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid