继承 Microsoft.Xna.Framework.Game,
graphics设置参数时,更改为传入的句柄
通过this.Window.Handle获取内置FORM对象,将其设置TOP,确定不出现在显示器中,即可。
内置FORM的VisibleChanged事件订阅:当显示内置FORM时,将其设置设置成不可见!!!
public class WinGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
public WinGame()
{
graphics = new GraphicsDeviceManager(this);
drawHandle = IntPtr.Zero;
}
IntPtr drawHandle;
Form form;
public WinGame(Form form)
: this(form,form.Handle)
{
}
public WinGame(Form form, IntPtr drawHandle)
: this()
{
this.form = form;
this.drawHandle = drawHandle;
graphics.PreparingDeviceSettings += (s, e) =>
{
if (drawHandle == IntPtr.Zero) return;
e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = this.drawHandle;
Mouse.WindowHandle = this.DeviceDrawControl.FindForm().Handle; //mouse状态支持
};
if (drawHandle == IntPtr.Zero) return;
Form gameWindowForm = Control.FromHandle(this.Window.Handle) as Form;
gameWindowForm.FormBorderStyle = FormBorderStyle.None;
gameWindowForm.Top = -2000 + gameWindowForm.Height * -1;
gameWindowForm.VisibleChanged += (s, e) =>
{
if (!gameWindowForm.Visible) return;
gameWindowForm.Visible = !gameWindowForm.Visible;
};
}
protected override void BeginRun()
{
if (this.form != null)
{
this.form.FormClosing += (s, e) =>
{
base.Exit();
};
}
base.BeginRun();
}
public void SetBackColor(Color color)
{
if (this.drawHandle == IntPtr.Zero) return;
var control = Control.FromHandle(this.drawHandle);
control.BackColor = System.Drawing.Color.FromArgb(color.R, color.G, color.B);
}
}
XNA项目中,所有继承自Microsoft.Xna.Framework.Game,全部改成 从WinGame继承!
修改入口函数
static void Main(string[] args)
{
//using (Game1 game = new Game1())
//{
// game.Run();
//}
using (Form1 form = new Form1())
{
using (Game1 game = new Game1(form, form.GetPtr()))
{
form.Show();
game.Run();
}
}
System.Windows.Forms.Application.Exit();
}
form.GetPtr()方法,可以返回form自己的句柄,也可以是子控件的句柄!
这样不需要使用老外的那个事例中实现的XNA控件,又可以使用GAME的对象进行开发,方便!