Blue Theme Orange Theme Green Theme Red Theme
 
Ads by Lake Quincy Media
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » WPF » 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.

Total page views :  2242
Total downloads :  28
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Samples.zip
 
Become a Sponsor


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.

Have a nice day


Login to add your contents and source code to this article
 About the author
 
Ibrahim Ersoy
Im from Turkey. I have graduated from Computer Programming in 2005. I'm interested in programming for 6 years. I have worked with Visual Basic 6, Vb.NET, ASP/ASP.NET, HTML, C#.NET, SQL SERVER 2000/2005 AND XML. Now I'm working on System Programming and Database Architectures, Computer Graphics...
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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Samples.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.