Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » XNA » Windows Controls and WPF UserControls inside an XNA Game Project

Windows Controls and WPF UserControls inside an XNA Game Project

In this article we will be working on using Windows Controls and WPF UserControls inside an XNA Game Project.

Author Rank :
Page Views : 19838
Downloads : 372
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Samples.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


In this article we will be working on using Windows Controls and WPF UserControls inside an XNA Game Project.

They tell Windows Controls cant be used inside an XNA game let alone WPF. Well, that has been proved in this article.

Components:

Windows Controls we'll be using

  • Button
  • TextBox
  • CheckBox
  • ElementHost

Tools

XNA GS 3.1 veya Visual Studio 2008(SP1)
.NET Framework 3.5(SP1)

We are creating a new project:

image1.gif

Now we will add reference.Project->Add Reference and then choose "System.Windows.Forms" namespace.

image2.gif

And declare it on Game1.cs:

image3.gif

Note: You may need to declare and add reference to "System.Drawing" namespace as well.

TextBox Control:

An Input control we can use on Windows Forms.We add Textbox to our XNA project:

In anywhere we can declare variables:

TextBox text1 = new TextBox();

With that we have created a new Textbox variable.We are adding the code below to our Initialize() function.

   protected override void Initialize()
        {           
           
base.Initialize();
            text1.Location =
new System.Drawing.Point(40, 40);
            text1.BorderStyle = BorderStyle.None;
            text1.Multiline = true;
            text1.Size = new Size(400, 400);
            Control.FromHandle(Window.Handle).Controls.Add(text1);
        }

Let us explain : "Control.FromHandle(Window.Handle).Controls.Add(ornek);"

"Control.FromHandle" - helps us to call the handle we will add textbox.

"Control.FromHandle(Window.Handle)" We take the Handle of GameWindow class named Window.Game class is not a control.But because of GameWindow is a control that can be used on XNA project,we can call and add Windows Controls through it.We were able to add or remove any control while coding in Windows Forms because Windows Forms was itself a control too.Now let me tell you this: "Form class & GameWindow class looks alike".By thinking so we can make RAD(Rapid Application Development) in XNA just like we do while developing Windows Form Based Applications.

But if you run the project,you will not be able to enter a key inside TextBox class.

Because while Textbox class uses "System.Windows.Forms.Keys",XNA accepts only "XNA.Framework.Input.Keys".Although we cant make it with the Windows-Way,we will make it as we do on XNA Inputs.

string var_text1;

we add a string valuable that will store all the texts from your input and then assign to our text1 named TextBox class

protected override void Update(GameTime gameTime)
 {
  
base.Update(gameTime);
  
if (text1.Focused)
    {
     
KeyboardState ns = Keyboard.GetState();
     
foreach (Microsoft.Xna.Framework.Input.Keys a in ns.GetPressedKeys())
        {
          var_text1 = a.ToString();
          text1.Text += var_text1;
        }
     }
 }


"KeyboardState ns = Keyboard.GetState();" -> we get all the input from Keyboard("ns.GetPressedKeys()").This helps us to to write any key value to our Textbox.

If you wish you may not take all the keys,just use "if-else" structure and take any key you want to.

Let us run the project.Whats going to happen?

image4.gif

When we press a key,it wrote as we pressed 5 times.Let me explain this:

In Xna, every event happens on Update function depends on Gametime value.1 sec process is repeated 5 times so that the game window refreshes as we want.Why is it 1 sec/5? Because in continuous things like "chasing a car,shooting an opponent" we must see whats happening instantly.The user must feel like he is playing a "Real-time" game.Because of that Gametime repeats 5 times in 1 sec.Even 1 sec can differ sometime.

Lets go back to our project.How we will solve this?

create an int variable and query it on Update function.

int
ct = 0; //the start value must be 0 so it cant be repeated.

Then update our Update function seen below:

protected override void Update(GameTime gameTime)
 {
  
base.Update(gameTime);
  
if (text1.Focused)
    {
      ct = ct -1;
     
if(ct < 0)
       {
         ct = 5;
       }

     if(ct == 0)
       {
        
KeyboardState ns = Keyboard.GetState();
        
foreach (Microsoft.Xna.Framework.Input.Keys a in ns.GetPressedKeys())
          {
           var_text1 = a.ToString();
           Text1.Text += var_text1;
          }
       }
     }
  }


And you can enter any value without repeating:

image5.gif

Thats it! You have created a Textbox control inside an XNA Window...

BUTTON Control:

Button control helps us to accept a process.In this section i will be talking about how to add a button control and its eventhandler.

We declare our Button Class first.

Button btn = new Button();

To add this inside project-update Initialize function just like below:

protected override void Initialize()
 {            
   base.Initialize();
   btn.Text = "Press Me!";
   btn.Location = new System.Drawing.Point(50, 50);
   btn.FlatStyle = FlatStyle.Popup;
   Control.FromHandle(Window.Handle).Controls.Add(btn);
 }

Now lets write down a simple EventHandler that will show us a MessageBox.

protected override void Initialize()
  {           
   
base.Initialize();
    btn.Text =
"Press Me!";
    btn.Location =
new System.Drawing.Point(50, 50);
    btn.FlatStyle =
FlatStyle.Popup;
    btn.Click +=
new System.EventHandler(ButtonClick);
   
Control.FromHandle(Window.Handle).Controls.Add(btn);
  }

private void ButtonClick(object sender, EventArgs e)
  {
   
MessageBox.Show("Button is Clicked!");
  }


By doing so we have added "Windows Control-Based" events inside XNA Game.

image6.gif

CHECKBOX Control:

Checkbox control helps us to select multi-options.

We declare it as seen below:

CheckBox cb = new CheckBox();

Using it:

protected
override void Initialize()
 {           
  
base.Initialize();
   cb.CheckState =
CheckState.Unchecked;
   cb.Location =
new System.Drawing.Point(50, 50);
   cb.Text =
"Yes";
   cb.BackColor = System.Drawing.
Color.CornflowerBlue;
  
Control.FromHandle(Window.Handle).Controls.Add(cb);
 }

image7.gif

Lets create an eventhandler and change the text value of checkbox object.

protected
override void Initialize()
 {           
  
base.Initialize();
   cb.CheckState =
CheckState.Indeterminate;
   cb.Location =
new System.Drawing.Point(50, 50);
   cb.Text =
"Indeterminate";
   cb.BackColor = System.Drawing.
Color.CornflowerBlue;
   cb.CheckStateChanged +=
new EventHandler(CBChanged);
  
Control.FromHandle(Window.Handle).Controls.Add(cb);
 }

private void CBChanged(Object sender, EventArgs e)
 {
 
if (cb.CheckState == CheckState.Unchecked)
     {
       cb.Text =
"No";
     }
 
else if (cb.CheckState == CheckState.Checked)
     {
       cb.Text =
"Yes";
     }
 }


We have changed the code a little bit.

Check=Checked
No Check=Unchecked
Both of Them=Indeterminate

Lets run it!

Indeterminate Mode:

image8.gif

Unchecked Mode:

image9.gif

Checked Mode:

image10.gif

I have explained Windows controls as detailed as i can.Now lets talk about the most exciting feature: WPF!

WPF User Controls:

WPF User Controls are the most exciting controls we can add inside XNA Game.

But first we need to add some references that a WPF Application alone needs:

  • Presentation Core
  • Presentation Framework
  • UIAutomationProvider
  • WindowsBase
  • WindowsFormsIntegration

After that we will be adding our pre-made WPFUserControl from Project->"Add Existing Item..."

image11.gif

Find the files with Windows Markup Files & C# Source file and add them:

image12.gif

Now what we will do is to add them to our project as we have done before.

You can add the namespace we used for WPF UserControl.

using WindowsFormsApplication1;  //That's the Namespace we have used inside WPF UserControl

Inside this WPF User Control we have added a combobox and an event "SelectionChanged" which shows us message for the selected item.

Code of WPF UserControl:

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
   
ComboBoxItem cbi = ((ComboBox)sender).SelectedItem as ComboBoxItem;
   
MessageBox.Show(cbi.Content.ToString());
  }

XAML of WPF UserControl:

<UserControl x:Class="WindowsFormsApplication1.Kontrol1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <Grid>
        <ComboBox Height="23" Margin="48,70,132,0" Name="comboBox1" VerticalAlignment="Top" SelectionChanged="comboBox1_SelectionChanged">
            <ComboBoxItem>1</ComboBoxItem>
            <ComboBoxItem>2</ComboBoxItem>
            <ComboBoxItem>3</ComboBoxItem>
            <ComboBoxItem>4</ComboBoxItem>
        </ComboBox>
    </Grid>
</
UserControl>

Lets add the control!

Kontrol1 kontrol11 = new Kontrol1();

We declared the control.

Then inside "Initialize()" function call our control named Kontrol11...

protected override void Initialize()
 {           
  
base.Initialize();
  
//ElementHost object helps us to connect a WPF User Control.
   ElementHost elementHost1 = new ElementHost();
   elementHost1.Location =
new System.Drawing.Point(308, 69);
   elementHost1.Name =
"elementHost1";
   elementHost1.Size =
new System.Drawing.Size(350, 181);
   elementHost1.TabIndex = 1;
   elementHost1.Text =
"elementHost1";
   elementHost1.Child =
this.kontrol11;
  
Control.FromHandle(Window.Handle).Controls.Add(elementHost1);
 }

As you can see above we have added a WPF UserControl to our project

Lets run this project.Whats going to happen?

image13.gif

Yes Different UIS such as XAML cannot be used in directly inside an XNA Game.For that we must convert it to Single-Threaded.

Open your Program.cs file:

Change as it is:

using System;

namespace DemoTest
{
   
static class Program
    {
        [
STAThread]
       
static void Main(string[] args)
        {
           
using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }
}


[STAThread] Helps us to achieve this.Now our project is Single Threaded.And call any different UIs inside XNA!

image14.gif

As you can see we have added it inside XNA Game!

image15.gif

We are selecting an item and then:

It shows us the selected value.

image16.gif

In this article I have written as detailed as much to explain how we can do all of this inside XNA Game.

By doing so you have integrated Windows Controls and WPF User Controls inside XNA!

I will tell much more about REXA(Rich-Effects XNA Applications) in the following days.

Update:   FULL SCREEN

As you well know these samples run Windowed Mode.But what if they were running Full Screen?

If we use XNA's graphics.ToggleFullScreen() or graphics.IsFullScreen=true  then all the things we have used -like Windows Controls and Dialogs- will disappear.Thats because Direct3D that XNA uses will take over the control and remove all the Window-based controls and dialogs from full screen view.

If we cant use XNA Framework for full screen what are we going to do?

It is easy to call a one-line code for full screen,isnt it? Well what are you going to do when you face something like that not able to see Windows Controls or anything related to Windows Object Model?

Theres a solution! : We will develop it the "Windows-Way"..

We will be using Windows API for Full Screen.So what i suggest you is to follow the steps then you will find it most easy:

1) Add these references by coding:

using System.Runtime.InteropServices;

2) Add Windows API declarations:

[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndIntertAfter, int X, int Y, int cx, int cy, int uFlags);
[DllImport("user32.dll")]

private static extern int GetSystemMetrics(int Which);

 

private const int SM_CXSCREEN = 0;

private const int SM_CYSCREEN = 1;

private IntPtr HWND_TOP = IntPtr.Zero;

private const int SWP_SHOWWINDOW = 64;

These are going to show full screen or restore Windowed Mode.

3) Get Screen Values:

public
int ScreenX
{
  get
  {
    return GetSystemMetrics(SM_CXSCREEN);
  }
}
public int ScreenY
{
  get
  {
    return GetSystemMetrics(SM_CYSCREEN);
  }
}

4) Write Full Screen & Restore Codes:

private
void FullScreen()
{
    Form.FromHandle(Window.Handle).FindForm().WindowState=FormWindowState.Maximized;
    Form.FromHandle(Window.Handle).FindForm().FormBorderStyle = FormBorderStyle.None;
    Form.FromHandle(Window.Handle).FindForm().TopMost = true;
    SetWindowPos(Window.Handle, HWND_TOP, 0, 0, ScreenX, ScreenY, SWP_SHOWWINDOW);
}
private void Restore()
{
    Form.FromHandle(Window.Handle).FindForm().WindowState = FormWindowState.Normal;
    Form.FromHandle(Window.Handle).FindForm().FormBorderStyle = FormBorderStyle.FixedDialog;
    Form.FromHandle(Window.Handle).FindForm().TopMost = false;
}

5) For calling these 2 functions we will write a code @ Update function:

KeyboardState
newstat = Keyboard.GetState();
if (newstat.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Escape))
{
   FullScreen();
}
else if (newstat.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Space))
{
   Restore();
} 

If we click on Escape the game will run on Full Screen.If we press Space it will restore the Windowed Mode.

Lets run the updated part and see what happens:

Windowed Mode:

1.gif
FULL SCREEN:

2.gif 
Thats it! We have successfully Run our project in Full Screen.As you can see its very simple isnt it?

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Ibrahim Ersoy
Ibrahim Ersoy lives in Turkey, Istanbul. He helps running and managing C# Corner. He is a Software Consultant (Sharepoint) and MindCracker MVP. He writes about cutting-edge Microsoft Technologies including XNA, Sharepoint, LINQ, SQL Server and Windows Phone 7 Development besides lately he is interested in iOS,Android and BlackBerry development.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Thanks Ibrahim by Mike On February 2, 2010
Nice article,

I like how you bring the windows world into XNA.
Reply | Email | Modify 
Re: Thanks Ibrahim by Ibrahim On February 2, 2010
Thank you Mike :) I'll write much more in the future.I've been working on "GUI Editor for XNA".An Article about "how to make a basic GUI Editor" might come in anytime :)
Reply | Email | Modify 
Thanks. (Broken link for samples.zip?) by Roger On February 9, 2010

Nice article. Thanks for taking the time to write it. By the way, the samples html link appears to be broken.

Reply | Email | Modify 
Re: Thanks. (Broken link for samples.zip?) by Ibrahim On February 19, 2010
Thanks Roger for reading,

Broken link problem is solved.
Reply | Email | Modify 
Full Screen problems by Torpor On April 8, 2010

Cool tricks and good explanation but it had a problem when you go fullscreen (graphics.IsFullScreen = true;) the button, in the example seems to blink.


You know how to solve it?

Thanks and good job.

(Sorry for my english)

Reply | Email | Modify 
Re: Full Screen problems by Ibrahim On April 10, 2010
Thank you for reading,

Yes unfortunately when toggled fullscreen.Direct3D takes over the control and disables all the Windows-based objects.This is a general problem sadly.

Thats why i have made it Windowed mode :)

Of course theres always a solution!

We have to use the Windows-way for full screen.I will be updating the article for fullscreen.

Thank you!


Reply | Email | Modify 
thanks. by Torpor On April 23, 2010

You're Great!!!! :)

Good job man.

Reply | Email | Modify 
Re: thanks. by Ibrahim On April 28, 2010
Dont mention it! :)

I will continue sharing my knowledge in here.

Thanks for reading again
Reply | Email | Modify 
Updates for XNA 4 w WPF? by Laurence On March 29, 2011
Wondering if you have any new/update samples for the latest version of VS 2010 and XNA 4 that mixes WPF and XNA 3D Graphics?
Reply | Email | Modify 
Re: Updates for XNA 4 w WPF? by Ibrahim On April 10, 2011
Hi Laurence, I wish i could do that.Im in the army so i cant write any tutorial until my service ends: 13 months. Cheers!
Reply | Email | Modify 
thanks Ibrahim by Dionisio On November 15, 2010

this example has been very helpful to me for learning how to use WinForms and WPF within XNA.

good job!

thanks


Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.