Xbox LIVE Indie Games
Sort Discussions: Previous Discussion Next Discussion
Page 1 of 2 (50 posts) 1 2 Next >

A better way to embed XNA into WinForms (full source)

Last post 7/29/2011 2:11 AM by Ant2010. 49 replies.
  • 5/21/2007 3:45 PM

    A better way to embed XNA into WinForms (full source)

    I thought for sure I had figured out a nice way to embed XNA windows into Winform controls (after numerous hours in Lutz's reflector). The full code is below (built loosely off the official Tutorial1 code). Alas, it is so slow! Somebody help me, please. Thanks for your time. Look at the variable called wannaGoSlow.


    #region Using Statements
    using System;
    using System.Collections.Generic;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Audio;
    using Microsoft.Xna.Framework.Content;
    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework.Input;
    using Microsoft.Xna.Framework.Storage;
    using System.Windows.Forms;
    using System.Security;
    using System.Runtime.InteropServices;
    #endregion

    namespace WindowsGame1
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            static void Main(string[] args)
            {
                Application.EnableVisualStyles(); // must be done before creating any forms
                Application.SetCompatibleTextRenderingDefault(false); // must be done before creating any forms
                Application.Run(new Form1());
            }
        }

        public class Form1 : Form
        {
            private Game1 game = null;
            public Form1()
            {
                InitializeComponent();
                SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
                UpdateStyles();
                // handle the resize here because the XNA one is totally busted:
                this.ClientSizeChanged += Form1_ClientSizeChanged;
                game = new Game1();
                game.FpsUpdated += new FpsDelegate(game_FpsUpdated);

                Form form = Form.FromHandle(game.Window.Handle) as Form;
                bool wannaGoSlow = true;
                if (wannaGoSlow)
                {
                    form.FormBorderStyle = FormBorderStyle.None;
                    form.Dock = DockStyle.Fill;
                    form.TopLevel = false;
                    form.Parent = this;
                    Controls.Add(form);
                }
                form.Visible = true;

                Application.Idle += Application_Idle;
            }

            void Form1_ClientSizeChanged(object sender, EventArgs e)
            {
                if (game != null)
                    game.SetAspectRatio(Width, Height);
            }

            void game_FpsUpdated(Game sender, int fps)
            {
                Text = "FPS: " + fps.ToString();
            }

            void Application_Idle(object sender, EventArgs e)
            {
                while (AppStillIdle())
                    game.Tick();
            }

            private bool AppStillIdle()
            {
                NativeMethods.Message msg;
                return !NativeMethods.PeekMessage(out msg, Handle, 0, 0, 0);
                // not sure if that should be IntPtr.Zero or Handle or game.Window.Handle
            }

            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                Application.Idle -= Application_Idle;
                this.ClientSizeChanged -= Form1_ClientSizeChanged;
                game.Dispose();

                if (disposing && (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.components = new System.ComponentModel.Container();
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.Text = "FPS: calculating";
            }

            #endregion
        }

        public delegate void FpsDelegate(Microsoft.Xna.Framework.Game sender, int fps);

        /// <summary>
        /// This is the main type for your game
        /// </summary>
        public class Game1 : Microsoft.Xna.Framework.Game
        {
            GraphicsDeviceManager graphics;
            ContentManager content;

            public Game1() : base()
            {
                IsMouseVisible = true;           
                graphics = new GraphicsDeviceManager(this);
                graphics.SynchronizeWithVerticalRetrace = false;
                graphics.ApplyChanges();
                content = new ContentManager(Services);

                // we're going to cut all the init from the run code and put it here:
                IGraphicsDeviceManager graphicsDeviceManager = this.Services.GetService(typeof(IGraphicsDeviceManager)) as IGraphicsDeviceManager;
                if (graphicsDeviceManager != null) // should have been added by new GraphicsDeviceManager
                {
                    graphicsDeviceManager.CreateDevice();
                    // base BeginDraw relies on this next line; see MS Feedback item 277959
                    this.GetType().BaseType.GetField("graphicsDeviceManager", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(this, graphicsDeviceManager);
                }

                Initialize();
            }

            /// <summary>
            /// Allows the game to perform any initialization it needs to before starting to run.
            /// This is where it can query for any required services and load any non-graphic
            /// related content.  Calling base.Initialize will enumerate through any components
            /// and initialize them as well.
            /// </summary>
            protected override void Initialize()
            {
                base.Initialize();
                this.BeginRun();

                // gameTime should be protected, not private: see MS Feedback item 277969
                GameTime gt = this.GetType().BaseType.GetField("gameTime", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(this) as GameTime;
                this.Update(gt);
                // doneFirstUpdate should be set in base.Update(): see MS Feedback item 277975
                this.GetType().BaseType.GetField("doneFirstUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(this, true);
            }

            protected override void Dispose(bool disposing)
            {
                this.EndRun();
                base.Dispose(disposing);
            }


            //3d model to draw
            Model myModel;

            /// <summary>
            /// Load your graphics content.  If loadAllContent is true, you should
            /// load content from both ResourceManagementMode pools.  Otherwise, just
            /// load ResourceManagementMode.Manual content.
            /// </summary>
            /// <param name="loadAllContent">Which type of content to load.</param>
            protected override void LoadGraphicsContent(bool loadAllContent)
            {
                if (loadAllContent)
                    myModel = content.Load<Model>("Content\\Models\\p1_wedge");
            }

            /// <summary>
            /// Unload your graphics content.  If unloadAllContent is true, you should
            /// unload content from both ResourceManagementMode pools.  Otherwise, just
            /// unload ResourceManagementMode.Manual content.  Manual content will get
            /// Disposed by the GraphicsDevice during a Reset.
            /// </summary>
            /// <param name="unloadAllContent">Which type of content to unload.</param>
            protected override void UnloadGraphicsContent(bool unloadAllContent)
            {
                if (unloadAllContent == true)
                    content.Unload();
            }

            //time since last FPS update in seconds
            double deltaFPSTime = 0;
            int fps = 0;
            /// <summary>
            /// Allows the game to run logic such as updating the world,
            /// checking for collisions, gathering input and playing audio.
            /// </summary>
            /// <param name="gameTime">Provides a snapshot of timing values.</param>
            protected override void Update(GameTime gameTime)
            {
                //if (GamePad.GetState(PlayerIndex.One).Buttons.Back == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                //    this.Exit();


                // The time since Update was called last
                double elapsed = gameTime.ElapsedGameTime.TotalSeconds;
                deltaFPSTime += elapsed;
                if (deltaFPSTime > 1)
                {
                    if (FpsUpdated != null)
                        FpsUpdated(this, fps);
                    deltaFPSTime -= 1;
                    fps = 0;
                }

                modelRotation += (float)gameTime.ElapsedGameTime.TotalMilliseconds * MathHelper.ToRadians(0.1f);

                base.Update(gameTime);
            }

            public event FpsDelegate FpsUpdated;

            //Position of the model in world space, and rotation
            Vector3 modelPosition = Vector3.Zero;
            float modelRotation = 0.0f;

            //Position of the Camera in world space, for our view matrix
            Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);


            private float aspectRatio = 1;
            public void SetAspectRatio(int width, int height)
            {
                graphics.PreferredBackBufferWidth = width;
                graphics.PreferredBackBufferHeight = height;
                aspectRatio = (float)width / (float)height;
                graphics.GraphicsDevice.Reset();
            }

            /// <summary>
            /// This is called when the game should draw itself.
            /// </summary>
            /// <param name="gameTime">Provides a snapshot of timing values.</param>
            protected override void Draw(GameTime gameTime)
            {
                fps++;
                graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

                //Copy any parent transforms
                Matrix[] transforms = new Matrix[myModel.Bones.Count];
                myModel.CopyAbsoluteBoneTransformsTo(transforms);

                //Draw the model, a model can have multiple meshes, so loop
                foreach (ModelMesh mesh in myModel.Meshes)
                {
                    //This is where the mesh orientation is set, as well as our camera and projection
                    foreach (BasicEffect effect in mesh.Effects)
                    {
                        effect.EnableDefaultLighting();
                        effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(modelRotation)
                            * Matrix.CreateTranslation(modelPosition);
                        effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
                        effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
                            aspectRatio, 1.0f, 10000.0f);
                    }
                    //Draw the mesh, will use the effects set above.
                    mesh.Draw();
                }
                base.Draw(gameTime);
            }
        }

        public static class NativeMethods
        {
            [StructLayout(LayoutKind.Sequential)]
            public struct Message
            {
                public IntPtr hWnd;
                public UInt32 msg;
                public IntPtr wParam;
                public IntPtr lParam;
                public UInt32 time;
                public Point p;
            }

            [SuppressUnmanagedCodeSecurity] // We won't use this maliciously
            [DllImport("User32.dll", CharSet = CharSet.Auto)]
            public static extern bool PeekMessage(out Message msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, uint flags);
        }
    }
  • 5/22/2007 1:30 AM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Very nice!

    I achieved the same by recreating almost the entire GraphicsDeviceManager to run inside the client area of a Windows.Forms UserControl. Even then, I had to hack the Idle loop quite a bit to allow for multiple instances of the control simultaneously without suppressing the idle message for the Application itself. The idea of just reparenting the Window created by the XNA GraphicsDeviceManager never occured to me :>

    Are there any side effects (eg. clicking in the drawing area unfocuses the outer window)?
    Apart from the speed issue, does this work with multiple XNA windows at the same time?

    If you're interested, my variant of Windows.Forms XNA can be found here (full source included as well)
    http://www.nuclex.org/news/2007/05/14/xna-windows-forms-usercontrol

    Cheers,
    -Markus-
  • 5/22/2007 10:50 AM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Very clever, I was wondering how you did some things reading through the post but I see now (I've tried this myself, ended up rewriting the game class).  I wish this was around a few months ago, I could have used it :)  This part in particular is what I was missing:


                // gameTime should be protected, not private: see MS Feedback item 277969
                GameTime gt = this.GetType().BaseType.GetField("gameTime", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(this) as GameTime;
                this.Update(gt);
                // doneFirstUpdate should be set in base.Update(): see MS Feedback item 277975
                this.GetType().BaseType.GetField("doneFirstUpdate", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(this, true);


    I'll definately vote for these on connect.
  • 6/2/2007 12:51 PM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Thanks.. this is the start I needed.
  • 6/2/2007 2:37 PM In reply to

    XNA Internet Explorer Object Model

    Thanks for idea..

    Now.. time to Internet explorer embeded model

    i started to create game control on ie.. now, when i use any system resource .net framework blows up... if i can solve security problems on .net i will post my 'style'.. .;)

  • 7/9/2007 11:03 PM In reply to

    WinForms with minimal fuss

    Well after studying your code....it got me to thinking.

    .....all I want to do is draw on something besides the form client area, and that's the ONLY change I want to make to the Game calss....and then it hit me.

    #1 Create a regular Windows Game Template (NOT a WinForm)
    #2 Add a reference to System.Windows.Forms to your project
    #3 Add a using System.Windows.Forms to your Game class

    Here's where it gets pretty, the OnPrepareDeviceSettings of the GraphicsDeviceManager allows us to set the handle for the graphics device BEFORE it gets created.

    So all we have to do is implement the event signature and add it as a event handler and presto.

    Here's a snippet of my implementation:

        /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
    GraphicsDeviceManager graphics;
    ContentManager content;
    Panel drawSurface;

    private void OnPreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs args)
    {
    args.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface.Handle;
    }

    public Game1()
    {
    graphics = new GraphicsDeviceManager(this);
    graphics.PreparingDeviceSettings += OnPreparingDeviceSettings;
    content = new ContentManager(Services);
    this.IsMouseVisible = true;
    drawSurface = new Panel();
    drawSurface.Width = 300;
    drawSurface.Height = Form.FromHandle(this.Window.Handle).Height;
    Form.FromHandle(this.Window.Handle).Controls.Add(drawSurface);
    }


  • 7/10/2007 1:55 PM In reply to

    Re: WinForms with minimal fuss

    It would be neat if the XNA framework made an override to the Game class constructor that takes an IntPtr, that would be nice :) No messing with custom graphics device implementation, no messing with viewports or game loops, just create the game, it knows how to draw itself to the handle passed to the constructor and hopefully the regular windows forms stuff (mouse, keyboard, etc.) works outside of the panel.

    Vote for this now! ---> https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=286790&SiteID=226

  • 7/10/2007 2:05 PM In reply to

    Re: WinForms with minimal fuss

  • 7/10/2007 2:12 PM In reply to

    Re: WinForms with minimal fuss

    The last bit of code was very nice, although it doesnt quite serve my purpose and im too much of a c# noob to get it working.

    I've created my own form and i want to display the XNA environment in a picturebox or equivalent, so i can place controls down the sides.  Problem is the main XNA window still opens as well as my form, although the XNA window is not updated.

    Anyway to stop the main XNA window opening and use a control to display the XNA on my custom form?
  • 7/10/2007 6:14 PM In reply to

    Re: WinForms with minimal fuss

    Gibba:
    The last bit of code was very nice, although it doesnt quite serve my purpose and im too much of a c# noob to get it working.

    I've created my own form and i want to display the XNA environment in a picturebox or equivalent, so i can place controls down the sides.  Problem is the main XNA window still opens as well as my form, although the XNA window is not updated.

    Anyway to stop the main XNA window opening and use a control to display the XNA on my custom form?


    To answer your question, No.  You cant prevent the Form that the Game class creates from displaying, and you really shouldnt want too.  Well, you probably could if you cast the window handle back into a form and set the forms visible property too false.  But all that's going to get you is a drawing surface that you cant see once the game starts.

    The thing I realized after several attempts is that, #1 The Game class is going to create its own drawing surface using the entire client area of the form, #2 The Game class needs access to the Application message loop. 

    #2 is really nasty, because if it doesnt, then you have to implement your own game loop code that manually calls Game.Tick().

    So I decided to go the other way, instead of displaying XNA inside another form...I tried to get XNA to not use the entire surface of the form it's going to create anyway.

    Until they do another release I dont see another way.
  • 9/9/2007 2:34 PM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Thx for the great code,

    I'm doing following
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
        public partial class IceGameForm : Form
    {
    private ContentManager content;
    public ContentManager ContentManager { get { return content; } }

    protected GraphicsDevice myGraphicsDevice;

    private IceWindow myRenderWindow;
    public IceWindow IceWindow { get { return myRenderWindow; } set { myRenderWindow = value; } }

    protected GameTime gameTime;

    private DateTime oldTime, currentTime, startTime;
    private TimeSpan delta;
    private bool done = false;

    private const float timeStep = 1000f / 60f; // 60 fps update
    private float nextUpdate = 0;

    private bool isFixedTimeStep = false;

    public IceGameForm()
    {
    myRenderWindow = new IceWindow();
    }

    protected virtual void Initialize()
    {
    FormClosing += new FormClosingEventHandler(ShutDown);

    startTime = currentTime = DateTime.Now;

    if (myRenderWindow.RenderControl == null)
    throw new Exception("No Control to render to");

    CreateDevice();
    content = new ContentManager(new GraphicsDeviceService(myGraphicsDevice));

    myRenderWindow.RenderControl.Resize += new EventHandler(ResizeWindow);
    }

    public void CreateDevice()
    {

    PresentationParameters pp = new PresentationParameters();
    pp.IsFullScreen = false;
    pp.BackBufferCount = 1;
    pp.BackBufferHeight = myRenderWindow.RenderControl.Height;
    pp.BackBufferWidth = myRenderWindow.RenderControl.Width;

    myGraphicsDevice = new GraphicsDevice(
    GraphicsAdapter.Adapters[0],
    DeviceType.Hardware,
    myRenderWindow.RenderControl.Handle,
    CreateOptions.HardwareVertexProcessing,
    pp);
    }

    protected void ShutDown(object sender, FormClosingEventArgs e)
    {
    done = true;
    e.Cancel = true;
    }

    protected virtual void LoadGraphicsContent(bool loadAllContent)
    {
    if (loadAllContent)
    {

    }
    }

    protected virtual void UnLoadGraphicsContent(bool unloadAllContent)
    {
    if (unloadAllContent)
    {
    content.Unload();
    }
    }

    public virtual void Update(GameTime gametime)
    {
    }

    private void BeginDraw()
    {
    myGraphicsDevice.Clear(Color.CornflowerBlue);
    }

    private void Draw(GameTime gametime)
    {
    }

    private void EndDraw()
    {
    myGraphicsDevice.Present();
    }

    private void ResizeWindow(object sender, EventArgs e)
    {
    if (myRenderWindow.allowUserResizing == false)
    {
    return;
    }

    if (myRenderWindow.RenderControl.Width < 1 || myRenderWindow.RenderControl.Height < 1)
    return;

    myGraphicsDevice.PresentationParameters.BackBufferWidth = myRenderWindow.RenderControl.Width;
    myGraphicsDevice.PresentationParameters.BackBufferHeight = myRenderWindow.RenderControl.Height;

    myGraphicsDevice.Reset();
    }

    public void Run()
    {
    Initialize();

    LoadGraphicsContent(true);

    while (!done)
    {
    oldTime = currentTime;

    currentTime = DateTime.Now;
    delta = currentTime - oldTime;

    if (isFixedTimeStep)
    {
    if (gameTime.ElapsedRealTime.TotalMilliseconds > nextUpdate)
    {
    Update(gameTime);
    myEngine.Tick();
    }

    }
    else
    {
    Update(gameTime);
    }
    BeginDraw();

    Draw(gameTime);

    EndDraw();

    Application.DoEvents();
    }
    UnLoadGraphicsContent(true);

    Close();
    }
    }

    As you can see it's rather old-school game-looping, and it works... the things is, XNA re-invented the wheel and made great mods to it... I don't feel re-re-inventing the wheel and use my own "timing"... is there a way to start the Gametime? as for now ..time stands still... in real life this would be great, in games rather stupid things don't you think? ;)

    hopefully one of the inhouse guru's knows a solution ...

    Greetz

  • 9/10/2007 4:20 PM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Mike,

    XNA 2.0 is going to address this issue head-on.  So we wont have to do any hacks to get our game to run inside of a form.  I wouldnt invest too much time in trying to get this to work as it'll all hopefully be taken care of.

    _-TS-_
  • 9/11/2007 1:57 PM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Thx Twinsnake,

    As the day and night progressed I started thinking further more the question, and as I already read somewhere else, in my editor I don't need any "animations", so  in my "game-form"-constructor I just do:
    gameTime = new GameTime();

    at that moment everything inside gameTime is set to "zero" and I pass this dummy gameTime further down the rendering stuff.

    So, If some one wants I can past more code or even "blog" it somewhere ;)

    Greetz
    Mike
  • 11/3/2007 8:19 AM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Apparently, the WinForms/XNA implementation has been cut for time reasons. So...More discussion?

    @TwinSnakes007: Your code doesn't make the form the drawing surface; it draws a form in the window.
  • 11/27/2007 10:28 AM In reply to

    Re: A better way to embed XNA into WinForms (full source)

    Narf the Mouse:
    Apparently, the WinForms/XNA implementation has been cut for time reasons. So...More discussion?

    @TwinSnakes007: Your code doesn't make the form the drawing surface; it draws a form in the window.


    Narf, my feeble attempt of a code snippet shows you how to tell XNA where to draw so that you can add custom controls for a GUI.  So instead of it taking up the entire screen on the form it creates, you are restricting it to a custom control.

    I havent looked at 2.0 to see if there's some new stuff to try.  I know they exposed alot of stuff that was hidden before.

    Really though, you'd only need to go this route if you want to use the content pipeline integration in your editor.

    _-TS-_
  • 11/27/2007 1:39 PM In reply to

    Re: WinForms with minimal fuss

    I tried this at first in 2.0 beta ( what TwinSnakes007 wrote) , but it still wont work sadly.

    I added a graphics.ApplyChanges(); after graphics.PreparingDeviceSettings += OnPreparingDeviceSettings and

    It entered the OnPreparingDeviceSettings part.

    But, if i read correctly here, the forms wont work because the XNA game part uses the loops (update, ect) of the form itself ?

    If that is the case, i find it hard to ever directly getting XNA working with forms, without using directx as MDX part (like setting own presentparameters ect ect).

    Doesnt that kinda break the "easy" part of even using XNA for game developement ?

    I mean, maybe its just me, but i see XNA more or less like a 3d engine (or 2d for that sake), but last i checked, most engine's allows you to attach it to a form.

    Maybe its just be babling, im kinda new to this XNA thing, went to it after i heard that MDX is gonna be "put to rest" and XNA would take over, so i thought ill jump on the wagon as soon as the 2.0 came with support for a normal version of visual studio.

    My thoughts was to create a wysiwyg editor where the -> form <- and -> engine <- part was seperated, so i could more or less copy the intire engine part to the game client for use.

    But like this, its not possible because, well it "is", but im going around the most of XNA to init grafics in my editor, so it would be the same in client, wich means i could almost have done it same way in MDX.

  • 11/27/2007 2:39 PM In reply to

    Re: WinForms with minimal fuss

    I filed a connect suggestion that they allow you to set the handle of the render target in the game class. That would solve all of the windows forms problems with XNA. Vote for it here:

    https://connect.microsoft.com/feedback/ViewFeedback.aspx?FeedbackID=286790&SiteID=226

  • 11/27/2007 2:45 PM In reply to

    Re: WinForms with minimal fuss

    hm i get a file not found on that url.

    would love to vote YES! on such a feature... it would make my day, mm week.. no year!.. :)

  • 11/27/2007 2:50 PM In reply to

    Re: WinForms with minimal fuss

    You need to have a connect account to be able to view connect issues. If you have a connect account with a different live ID than you are using here then the link also doesn't work - you will need to log into connect and then find the issue.

    http://connect.microsoft.com and see also How do I use Connect for XNA features and bugs

  • 11/27/2007 3:04 PM In reply to

    Re: WinForms with minimal fuss

    Ah, thanks Z, now it works :)

    Guess ill put my little project on hold for the time being, its not that pressing a matter right now, i can finish my tools i wrote (Pak virtual file system, Update creator ect). tweak em a bit and so on.

  • 11/28/2007 4:49 PM In reply to

    Re: WinForms with minimal fuss

    NightMarez:

    But, if i read correctly here, the forms wont work because the XNA game part uses the loops (update, ect) of the form itself ?

    If that is the case, i find it hard to ever directly getting XNA working with forms, without using directx as MDX part (like setting own presentparameters ect ect).



    NightMarez, maybe you can share your initialization code.  I just tried using XNA 2.0 and it works as expected. 

    If you need some help just let me know.

    As far as the API, I dont see what the big deal is.  All they need to do is give us a constructor that we can pass a handle of the form to draw on to the Game class when it gets created.  Only thing I can think of is they want our code to be portable to XBox without modification, and it probably wouldnt be if they did it that way.

    _-TS-_
  • 11/28/2007 5:04 PM In reply to

    Re: WinForms with minimal fuss

    TwinSnakes007:
    All they need to do is give us a constructor that we can pass a handle of the form to draw on to the Game class when it gets created.  Only thing I can think of is they want our code to be portable to XBox without modification, and it probably wouldnt be if they did it that way.


    I have no idea what the team is planning, but it is my suspicion that whatever solution they come up with will certainly not be 360 compatable and will live in a seperate, Windows-only assembly.

    If I had my way, it would take the form of a XnaView control which you could simply drag out of the toolbox onto a form. That would be nice because then you could easily make multiple viewports and such, but is actually substantially more sophisticated to setup and doesn't directly match the semantics of the Game class.

    It's never as easy as it first looks, especially when you have to write framework code that is going to be used by such a wide range of people. Even the seemingly simplist things have complications which can easily be overlooked by those who are not accustom to the framework-writing frame of mind. For example, a lot of people asked "Why isn't the chat pad supported in v1? Isn't it just a keyboard? It should work the same as any keyboard". The response was "because you can have more than one of them" and people said "oooooh. right." :-)
  • 11/28/2007 10:49 PM In reply to

    Re: WinForms with minimal fuss

    TwinSnakes007:

    The thing I realized after several attempts is that, #1 The Game class is going to create its own drawing surface using the entire client area of the form, #2 The Game class needs access to the Application message loop. 

    #2 is really nasty, because if it doesnt, then you have to implement your own game loop code that manually calls Game.Tick().

    So I decided to go the other way, instead of displaying XNA inside another form...I tried to get XNA to not use the entire surface of the form it's going to create anyway.

    Until they do another release I dont see another way.


    I would dearly love to see how you managed that, if indeed you did.
  • 11/29/2007 4:58 AM In reply to

    Re: WinForms with minimal fuss

    Actually it's not all that hard to create a windows form with a component that can draw the XNA stuffs.

    You can just hide the window that XNA creates, however Window.Hide() doesn't quite do the trick. So you have to thoroughly hide the whole thing. I noticed that no matter what you did to this window it wouldn't at all influence the drawing. However the big disadvantage of removing that window is that you lose all Input and you'll have to use the windows.form or the good old hwnd stuffs to catch key-presses and what not.

    I've actually managed to create a visual plugin for visual studio 2005 with XNA (yay me) so it's really do-able right now but like the rest of you guys I can't wait for a proper way to add a component to your form with minimal fuss.

    relevant code can be found here:
    http://www.wilcob.com/Wilco/Pastecode/6132/showpaste.aspx
  • 11/29/2007 11:09 AM In reply to

    Re: WinForms with minimal fuss

    EvanWeeks:
    TwinSnakes007:

    So I decided to go the other way, instead of displaying XNA inside another form...I tried to get XNA to not use the entire surface of the form it's going to create anyway.


    I would dearly love to see how you managed that, if indeed you did.




    The code is above.
Page 1 of 2 (50 posts) 1 2 Next > Previous Discussion Next Discussion
var gDomain='m.webtrends.com'; var gDcsId='dcschd84w10000w4lw9hcqmsz_8n3x'; var gTrackEvents=1; var gFpc='WT_FPC'; /*<\/scr"+"ipt>");} /*]]>*/
DCSIMG