XNA-與Win Form共存

XNA-與Win Form共存

XNA與winform結合可以用來作編輯類的工具軟體,可以直接看看在xna底下跑是什麼樣子。

首先開一個xna的專案,然後加入windows form,取名為MainForm:

image

然後再winform裡面加入一個panel,用來當做xna的畫面。我取名為XnaPanel。

然後為了讓xna可以取得此panel,我們要在winform內加上下列程式:

 


public Control Panel {
	get { return XnaPanel; }
}

然後再game的主程式增加下列程式碼:


using winform = System.Windows.Forms;

MainForm form;

public Game1(MainForm form) {
	graphics = new GraphicsDeviceManager(this);
	Content.RootDirectory = "Content";
	this.form = form;

	graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
	System.Windows.Forms.Form xnaWindow = (System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle((this.Window.Handle));
	xnaWindow.GotFocus += new EventHandler(delegate(object sender, EventArgs e) {
		((System.Windows.Forms.Form)sender).Visible = false;
		form.TopMost = false;
	});
}


private void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e) {
	e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = form.Panel.Handle;
}

 

 

主要作用是當設定繪圖裝置時,將輸出的地方改成winform的panel,並且在game本身的視窗開啟時讓他消失,

最後在program.cs裡加入以下程式碼:


static Game1 game;

static void Main(string[] args) {
	MainForm form = new MainForm();
	form.Disposed += new EventHandler(form_Disposed);
	using (game = new Game1(form)) {
		form.Show();
		game.Run();
	}
}

static void form_Disposed(object sender, EventArgs e) {
	game.Exit();
}

這樣啟動程式之後,xna的畫面就會顯示在winform裡的panel上了。

如此可以在xna的部份加上對外的控制介面,然後由winform呼叫。

範例程式:XNA-與Win Form共存.rar