What I learned to do was to start your main project as usual with a Windows Game (4.0) then add your winform.
Create a field to hold a reference to the Game1 class inside the form1 class
Game1 gameEntry
;
Set the modifier on your pictureBox to public.
In Program.cs :
replace everything in static void Main()
Form1 form = new Form1();
form.show();
// This line creates a Game1 object in the gameEntry field created earlier.
form.gameEntry = new Game1(form.pictureBox1.Handle, form, form.pictureBox1);
form.gameEntry.Run();
OR:
using (Form1 editorForm = new Form1())
{
editorForm.Show();
editorForm.gameEntry = new Game1(editorForm);
editorForm.gameEntry.Run();
}
This means we need to modify the constructor that comes with Game1.
System.Windows.Forms.Control gameForm;
public Game1(IntPtr drawingSurface, System.Windows.Forms parentForm, System.Windows.Forms.PictureBox pictureBox)
{
this.drawingSurface = drawingSurface;
this.parentForm = parentForm;
this.pictureBox = pictureBox;
// prepare graphics event
graphics.PreparingDeviceSettings +=
new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
gameForms = System.Windows.Forms.Control.FromHandle(this.Window.Handle);
//Tell the mouse it will be getting it's input through the pictureBox
Mouse.WindowHandle = drawSurface;
}
private void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
// Finally attach game1's draw ability to the picture box in winforms.
e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = drawSurface;
}
At this point you should be able to run the program and will have two windows. You probably don't want the game1 window showing so create an event to hide it.
private void gameForm_VisiblilityChanged(object sender, EventArgs e)
{
if (gameForm.Visible = true)
gameForm.Visible = false;
}