Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Building Basic Windows Applications

0.00/5 (No votes)
23 Oct 2009 1  
An Article that explains certain aspects of Windows Forms

Building Basic Windows Applications

Introduction: A Little History

There is a lot of documentation on Windows Forms. This paper is meant for the either the beginner or the intermediate enthusiast of Windows Forms. The majority of commercial applications will not be console applications. Instead they will use a user interface that contains controls in which the user can make things happen. The earlier Windows applications required the use of raw Windows APIs such as RegisterClass, CreateWindow, ShowWindow, GetMessage, TranslateMessage, and Dispatch Message. You needed a WinMain entry point in your application. Inside this function, you registered your application with Windows, created and showed a Window, and handled messages from the system Every Windows application has to have a message loop that collects Windows messages and dispatches them to the message handler function that you've registered through RegisterClass function. As a developer, most of your energy was directed towards handling Windows messages, such as WM_CREATE, WM_SIZE, or WM_CLOSE, that you had to create and pump into the system with PostMessage or SendMessage. This earlier type Windows development is tedious. The result is that application frameworks were built as an abstraction on top of all these Windows APIs. Frameworks like MFC and ATL were created to help developers solve business problems that on how to handle certain Windows messages. These frameworks provided the plumbing, or the template, of a Windows application.

Today's Windows applications are mainly based on Windows Forms, which provide a unified programming model for standard Windows application development. Knowing that it is the goal of the .NET Framework to embrace the web, a windows Forms desktop application can interact with the web and the web can interact with the desktop application. If the application is contained in a browser, then it is called a Web Form. If the application runs on the desktop, it is called a Windows Form. The Windows Forms architecture is relatively simple. It takes the form of controls and containers. Most user-interface classes in the System.Windows.Forms namespace derive from the Control class. If a control can contain another control, it is a container. This article will focus on Windows Forms development with the purpose of starting with the basics and progressing to developing a basic desktop game. While the applications show may appear generic and repetitive, they can be used as models to expand on.

Developing a Windows Forms Application by Hand

Events are the core of Windows Forms application and developing a Windows Forms application. When we develop a Windows Forms application by hand, we use Forms metaphor for Rapid Application Development of the user interface. To do this you derive from System.Windows.Forms.Form. From there you create widgets, like System.Windows.Forms.Label, and after that you set up the text, location and size of your widgets. Finally, you set up the event handlers to respond to any user interaction and add those widgets to the form's control collection

using System;
using System.Windows.Forms;
using System.Drawing;

  public class myForm : Form
  {
     private System.Windows.Forms.Label output;
     private System.Windows.Forms.Button cancel;
   
// create contructor for the Form, which must be the same name as the class    //itself
   
 public myForm()
     {
      // create the objects
       output = new  System.Windows.Forms.Label();
       cancel = new System.Windows.Forms.Button();
    
      // set the form's title
       Text = "Hello World from C# Forms";
      // setup output label; we have to tell it where to put the label
       output.Location = new System.Drawing.Point(20, 30);
       output.Text = "Hello World from C# Forms";
       output.Size = new System.Drawing.Size(200, 25);
       cancel.Location = new System.Drawing.Point(150, 200);
       cancel.Text = "&Cancel";
       cancel.Size = new System.Drawing.Size(110, 30);

      // set up the event handler
        cancel.Click += new System.EventHandler(this.onCancelclick);

      // add the controls
       Controls.Add(cancel);
       Controls.Add(output);
    } 
      // end constructor


     protected void onCancelclick(object sender, System.EventArgs e)
     {
       Application.Exit();
     }

     // now we need an entry point for the application
      public static void Main()
     {
        Application.Run(new myForm());
     }
   }

        

/****the output: ***/

a.JPG

Looking at the form, there is no reason why we cannot add some functionality to it. In fact we will design a game called “Lucky Seven”. Lucky Seven has three labels that contain integers that, when the “spin” button is clicked, are generated by the random number generator function in C#. Whenever the number seven appears, an image pops onto the form. We start by building a Visual C# Windows application and naming it MySeven. We drag and drop two buttons on the upper left hand corner and set their text properties two Spin and Close, respectively. We then drag four Label controls onto the surface of the form, three of which will form a row to the right of the spin button. Finally we drag and drop a picture control to the right of the fourth label, which resides underneath the Close button. Now the first three labels must have their properties set before we can write some code. Click the AutoSize property to false so that you can size the labels manually. Set the TextAlign property to Middle Center. Click the BorderStyle property and choose FixedSingle. Change the Font to New Times Roman, the font style to bold, and the point size to 24 and then click OK. Now set the Text property for those three labels with a numerical 0.

Now set the fourth label object (Label4) on the Form. Change the Text property to LuckySeven. Click the Font property and then click the ellipses button. Use the Font dialog box to the font to Arial, the font style to bold, and the point size to 18, and then click OK. Note that the Label Object’s size (the fourth label underneath the Close button)is updated and the label is resized automatically to hold the larger font size because the object’s AutoSize property is set to True. Now click the ForeColor property in the Properties window, and then click the arrow in the second column. Choose the Custom tab and select purple. Now the text that appears in the label box changes to purple. Now we are ready to set the properties for the last object, the Picture Box.

Click the picture box on the form. Click the SizeMode property in the Properties window and then in the second column click StretchImage. This property will force conform the size of an image to fit the box to scale. Click the Image property and the click the ellipses button in the second column. The Select Resource dialog box appears. In the Open dialog box, navigate to the c:\users\name\Pictures\SamplePictures folder and choose an image. Resize the picture box object to fix any distortion problems that you might see in the image. You might want to size it so that the picture box object to be 148 pixels wide by 138 pixels high. Now we change the picture box object’s property Visible to False so that image will be invisible when the program starts.

      b.JPG

Here is the code for Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Security;
using System.Text;
using System.Windows.Forms;


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Random r = new Random();
            pictureBox1.Visible = false;

            int rand1 = r.Next(1, 9);
            int rand2 = r.Next(1, 9);
            int rand3 = r.Next(1, 9);

            label1.Text = rand1.ToString();
            label2.Text = rand2.ToString();
            label3.Text = rand3.ToString();



            if (rand1 == 7 || rand2 == 7 || rand3 == 7)  // or is ||
            {
                pictureBox1.Visible = true;
            }

        }
    }

And here is the code for the main Program:

using System;
using System.Collections.Generic;
using System.Security;
using System.Windows.Forms;

  static class Program
    {
        
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

And finally, here is the Designer code generated by the IDE:

    partial class Form1
    {
        /// 
        /// Required designer variable.
        /// 
        private System.ComponentModel.IContainer components = null;

        /// 
        /// Clean up any resources being used.
        /// 
        /// ""disposing"" />true if managed resources should be disposed; otherwise, false.
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// 
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// 
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(24, 27);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "Spin";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(24, 80);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 1;
            this.button2.Text = "End";
            this.button2.UseVisualStyleBackColor = true;
            // 
            // label1
            // 
            this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label1.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(169, 27);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(100, 45);
            this.label1.TabIndex = 2;
            this.label1.Text = "0";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label2
            // 
            this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label2.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(275, 27);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(90, 45);
            this.label2.TabIndex = 3;
            this.label2.Text = "0";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label3
            // 
            this.label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label3.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(366, 27);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(100, 45);
            this.label3.TabIndex = 4;
            this.label3.Text = "0";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Arial", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(192)))));
            this.label4.Location = new System.Drawing.Point(24, 175);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(130, 22);
            this.label4.TabIndex = 5;
            this.label4.Text = "Lucky Seven";
            // 
            // pictureBox1
            // 
            this.pictureBox1.ErrorImage = null;
            this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
            this.pictureBox1.Location = new System.Drawing.Point(275, 108);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(191, 190);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 6;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.Visible = false;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(574, 325);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.PictureBox pictureBox1;
    }


Here is the game when a seven appears from the random number generator upon the click of the Spin button (obviously the Close button closes the application):

       Capture1.JPG

The Timer Control

Although timer objects aren’t visible at runtime, each timer is associated with an event procedure that runs every time the timer’s preset interval is set. You set a timer’s interval by using the Interval Property, and you activate the timer by setting the timer’s Enabled property to true. Once a timer is enabled, it runs constantly-executing its event procedure at the prescribed interval-until the user stops the timer or the timer is disabled. Create a small Visual C# Windows Forms application. Drag and drop a timer control and set the interval to 1000 (milliseconds) and its Enabled property to true. Set the form’s text property to “Clock”. Drag and drop a label control onto the center of the form. Set the AutoSize property to False, the Font to Times New Roman, bold, 24 point, leave the text property empty, and set the TextAlign property to MiddleCenter. Now, double-click the timer control and this code:

private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = System.DateTime.Now.ToString();
        }

And here is your basic digital clock:

c.JPG

Using the For loop to Create Sequences of Images

Assume we have four icons, each of which is one of those generic yellow faces. Each face show a different expression. We want to display these images, perhaps upon a condition that is reached, where the expression exemplifies that current state. We could use a for loop to iterate during a button click event handler where a Picture Box control portrays such an image. So, on this last note, let’s start a Visual C# Forms project and call it icons. We drag a picture box control onto the center of the form, and a button control underneath it. We set the BorderStyle property of the PictureBox to Fixed3D and we set the SizeMode to StretchImage. We then set the text property of the button control to “Display four faces”. We now double-click the “Display four faces” button to write the event handler:

File: Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace icon
{
  public partial class Form1 : Form
    {
   public Form1()
   {
   InitializeComponent();
  }

 private void button1_Click(object sender, EventArgs e)
 {

  for (int i = 1; i <= 4; i++)
   {
pictureBox1.Image = System.Drawing.Image.FromFile(@"c:\users\dave\desktop\face0" + i + ".ico");

  MessageBox.Show("click here for next face.");

         }
        }
      }
    }
    

Notice that I have stored the four icons on my desktop, so that is how the path is set to get passed as a parameter. Also notice that because we are dealing with icons to load. We do not look at the 4 icons as an array, so we do not initialize the variable to zero. Here is the code, but assembled to run on the console: You just type at the prompt: c:\..|.NET> type con > face.cs

From there you will have a cursor without a prompt. Copy and paste the code onto the prompt. Be sure and copy and paste those faces to your Desktop, or wherever you are confortable to configure your path:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
public class Form1 : Form
{
    private System.Windows.Forms.PictureBox pictureBox1;
    private System.Windows.Forms.Button button1;
     public Form1()
   {InitializeComponent();}
   private void InitializeComponent()
        {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.pictureBox1.Location = new System.Drawing.Point(35, 24);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(214, 164);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(81, 216);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(113, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Display 4 Faces";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.ClientSize = new System.Drawing.Size(303, 264);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
      }
         [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
  private void button1_Click(object sender, EventArgs e)
   {

  for (int i = 1; i <= 4; i++)
   {

   pictureBox1.Image = System.Drawing.Image.FromFile(@"c:\users\dave\desktop\face0" + i + ".ico");

  MessageBox.Show("click here for next face.");

         }
      }
   }

        x.JPG

        z.JPG

The clicking OK on the message box shows one the four faces, as they iterate during the sequence of buttons clicks.

References: .NET Framework Essentials, by Thuan Thai & Hoang Q. Lam

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here