3
votes

I have a simple XNA 4.0 Game written. I want to make a Windows Form User Control that will render this game, and provide the necessary interaction feedback (keyboard and mouse) back to XNA.

I have tried the following:

In XNA:

  • Redirect XNA's Game.GraphicsDevice to a RenderTarget2D.

  • Emit an event sending an object with KeyboardState and MouseState to be filled in by Windows Forms, at the beginning of Update()

In WinForms:

  • Capture the event, filling in KeyboardState and MouseState with data obtained by the usual keyboard and mouse events in Windows Forms.

  • On the OnPaint, call Game.RunOnFrame()

  • Get the RenderTarget2D from the game (as a texture).

  • Lock the texture's data, and try to paint it pixel by pixel in my user control's Graphics.

  • Another idea was just calling Game.Run() (o a new Thread) and emit an event in Game sending the RenderTarget2D.

I have found the following problems:

  • If I call Game.Run() I have no way to hide the game's window (which appears black, because I'm redirecting the render)

  • Game.Run() must be called on a different thread because it starts a new event loop (it calls Application methods), and then I'm painting in my user control from a different thread that it was created (bad, bad)

  • Locking a RenderTarget2D with Color, Vector4, and even Rgba32 doesn't appear to work for me (it says 'wrong structure size')

Any ideas?

Thanks in advance.

1
Dumb question - why would you want to do that?RQDQ
I think this tutorial & code sample covers exactly what you want to do: create.msdn.com/en-US/education/catalog/sample/…John McDonald
@RQDQ I think that's a not-so-well thought out comment. I can think of one reason you might want to embed an xna game in a winform: Creating a level editor.annonymously
@annonymously - I've actually been able to much better answer questions after understanding the fundamental goal. If the OP is indeed wanting to create a level editor, that would be helpful information.RQDQ

1 Answers

5
votes

There is a great code sample on xna's site about embedding xna in a winform. It takes you through all the steps. I make games for xbox, but I use this for the level editor we've made for our engine.

http://xbox.create.msdn.com/en-US/education/catalog/sample/winforms_series_1