0

我在 WinForm 中有一个嵌入式 XNA 4.0 游戏(用于关卡编辑器)。代码格式如下:

在游戏课上:

protected override void Initialize(){
    //initialization logic here  
    base.Initialize();

    SysWinForms.Form gameWindowForm(SysWinForms.Form)SysWinForms.Form.FromHandle(this.Window.Handle);
    gameWindowForm.Shown += new EventHandler(gameWindowForm_Shown);

    MYFORM = new Form1();
    MYFORM.HandleDestroyed += new EventHandler(myForm_HandleDestroyed);
    MYFORM.Show();
}


void myForm_HandleDestroyed(object sender, EventArgs e)
{
    this.Exit();
}

void gameWindowForm_Shown(object sender, EventArgs e)
{
     ((SysWinForms.Form)sender).Hide(); 
     //this line is important. When this line is commented the XNA + winForm windows are both shown. Also, the xna game is running in the winForm and it is running with modest speed. 
     //but when the line is not commented, than only the winForm window is shown and the xna game is shown inside it, but it is running with 0.5 frames/seconds
}

//The loadContent, unloadContent, update, and game constructor classes remain the same

protected override void Draw(GameTime gameTime)
{
     //draw logic here
     base.Draw(gameTime);
        //this is the actual trick that makes it all happen
        this.GraphicsDevice.Present(new Rectangle(controls.panel1.Location.X, controls.panel1.Location.Y, desired_Width, desired_Height), null, this.MYFORM.PanelHandle);
}

在 MYFORM 类中:

public IntPtr PanelHandle
{
    get
    {
        return this.panel1.IsHandleCreated ? this.panel1.Handle : IntPtr.Zero;
    }
}

还有一个自动生成的:

public System.Windows.Forms.Panel panel1;

如果有人查看代码,尤其是在“ void gameWindowForm_Shown(object sender, EventArgs e) ”函数中的注释,我将不胜感激。

提前谢谢

4

1 回答 1

2

从专家 Shawn Hargreaves 那里获取http://blogs.msdn.com/b/shawnhar/archive/2007/01/23/using-xna-with-winforms.aspx

经常看到人们试图在不寻常的地方使用 XNA Game 类,例如在 WinForms 应用程序中托管 XNA 游戏。

这通常是个坏主意。

Game 类的设计很简单,可以自动设置一切,让您开始编码。如果您正在做一些复杂的事情,并且想要更多地控制窗口创建方式的细节,那么这只会妨碍您。

Microsoft在此处此处提供代码示例,用于设置 XNA 图形设备以与 WinForms 一起使用。

于 2013-01-26T12:21:30.863 回答