Thursday, January 10, 2013

Windows Presentation Foundation #WPF - Coin Toss

Today at work,I could not find a coin to toss so decided to write a WPF program (Too lazy to search a site,download an app, find a penny on street to toss...)
This is a very basic Windows Presentation Foundation example.

Open Visual Studio 2010 -> Choose WPF Application -> Give it an appropriate name

















Click on the MainWindow.xaml file.Drag and Drop

  • Label - To display result
  • TextBoxes - Counters for toss
  • Button - Trigger toss event


The MainWindow.xaml looks like below

















Double click the button on MainWindow.xaml.cs and add the toss logic
I am generating a random number and dividing it by 2 to determine heads or tails.If the random number generated is even then its a Head else it is a Tail.


using System;
using System.Windows;
using System.Windows.Media;

namespace CoinToss

{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        int iHCounter = 0;
        int iTCounter = 0;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)

        {
            Random oRandom = new Random();
            int iRandomNumber = oRandom.Next(0, 10000);
            if (iRandomNumber % 2 == 0)
            {
                iHCounter++;
                textBox1.Text = "H:" + iHCounter.ToString();
                label1.Content = "HEADS";
                label1.Background = Brushes.Red;
            }
            else
            {
                iTCounter++;
                textBox2.Text = "T:" + iTCounter.ToString();
                label1.Content = "TAILS";
                label1.Background = Brushes.Green;
            }
        }
    }
}

Compile the solution and run it.Click the Toss button to see the result.






No comments: