Tuesday, January 5, 2010

Text scroll effect(C#)


Introduction

   In this tutorial, you will learn how to make a text scrolling effect using a label control. It's really quite simple, and it has a cool visual effect. To follow this tutorial step-by-step you will need .NET Framework and Visual Studio .NET installed on your machine.

Getting to work

   Let's begin by creating a new C# Project using Visual Studio .NET. Select File -> New Project -> Visual C# Project -> Windows Application. Name your project however you want, I will call it TextScroll.



   You are now in front of the Design view of your interface. First, we must create the user interface, after witch we will begin the coding part. The first thing we will do is add a Label control. To do that, select View -> Toolbox (or press Ctrl + Alt +X ). Select the Label control, drag and drop it onto our form. Now, we will need to adjust some properties of the Label. Select the Property window (if it's not visible, select View -> Properties Window, or just press F4). Change the TextAlign property to MiddleCenter ( by doing that, the text of the label will be displayed centered ). Also, the Text property of the label needs to display no text(from theProperties window, remove the text "label1", witch Visual Studio .NET adds it by default). It is preferred that we change the BackColor property (I changed it to SlateGray color, but you can use almost any color as long as the BackColor and ForeColor are different). Now change theForeColor to LightSalmon. Let's add a Button for starting the scroll. Set its Text property to Start Scrolling and the Name to btn_start. The next thing we need to add is a TextBox control, to allow the user to input the string that he wants to scroll. Visual Studio .NET will name theTextBox to textBox1, we will change this Name to tb_scroll. Go to the Text property and remove "textBox1" string.
   Another property we will need to change is MaxLength property to 30. This is the maximum number of characters that we allow the user to type into this control. The reason that we do this is that for a rather large number of characters, let's say 50, the label that we created earlier will display the text on two columns, making the scroll look rather ugly.
    Put a Label control above the TextBox created earlier, and set the Text property to "Please enter the string to be scrolled:". For now, the design part is over.
After there steps, your form should look something like this:


    Let's start creating some code, shall we?

    Double-click the TextBox control. Visual Studio .NET created a method calledtb_text_TextChanged. As its name says, this method occurs whenever the Text property of the TextBox changes. What we want to do is disable btn_start if we have no text in theTextBox. To do this, we need to add the following code:

if (tb_text.Text.Trim()="")
btn_start.Enabled = false;
else
btn_start.Enabled = true;
   The Trim() method, called with no argument, removes the extra spaces from the beginning and the end of the text. If the text property of tb_text is "", we want btn_start to be disabled, else we enable it.
   In the Design view, double-click the form's surface and a method called Form1_Load is created. In this method, we need to add the following:
btn_start.Enabled=false;
   The reason we do this is that when our application starts, the TextBox has no text in it, and we want btn_start to be disabled, because we have no text to scroll.   Let's go back to Design view and double-click btn_startVisual Studio will create a method called btn_start_Click. In this method we will write some code to begin the scrolling.
   First, we must understand how this scrolling works. We have a string, let's say "string to test the scrolling effect ". To create the effect, we must remove the last character of the string and set the label's Text property to the new string "string to test the scrolling effect". Now we must place the removed character(' ') in the first position of the string, so that we have " string to test the scrolling effect". We must repeat this action until we have the same string that we had when we started. The steps are:
string to test the scrolling effect
 string to test the scrolling effect
t string to test the scrolling effec
ct string to test the scrolling effe
ect string to test the scrolling eff
fect string to test the scrolling ef
ffect string to test the scrolling e
effect string to test the scrolling
effect string to test the scrolling
g effect string to test the scrollin
......................................................
string to test the scrolling effect
   So we will have to create a function that executes the scrolling until the form is closed.
   Now, we have to create a method that handles the scrolling, and call this method in thebtn_start_Click method. Let's create the following method:
private void ScrollText()
{
}
        Now we need to create the code that does the job.
System.Text.StringBuilder sb = new System.Text.StringBuilder(tb_text.Text+" ");
        StringBuilder class helps up to manipulate strings. We call the constructor that takes a string that we will play with. The reason that a space is appended at the end of the text is to separate the last and the first character. We need this class' methods Insert (to insert the character we remove from the end at the beginning of the string ) and Remove ( to remove the last character from the string ).
while (true)
{
char ch = sb[sb.Length-1];
sb.Remove(sb.Length-1,1);
sb.Insert(0,ch);
label1.Text = sb.ToString();
label1.Refresh();
System.Threading.Thread.Sleep(100);

}
    We do the scrolling until the user closes the window. We declare a variable of type char to hold the last character from the string,whitch we will remove using Remove() method. Next, we insert that character into the beginning of the string. We set the label text as the new text, refresh it and then we use the Sleep() method to pause the execution for 100 miliseconds. And that's the scroll.
   All we have to do now is call the ScrollText() method in the btn_start_Click method. We also need to add some extra code:
btn_start.Enabled=false;
ScrollText();
   Run the application and see this working.
   The main problem of the application is a non-responsive user interface. That's because we do the scroll operation is performed on the same thread that the user interface function run on. To avoid this, we need to create an asynchronous delegate.
   The first step is to declare a delegate at the beginning of the class and create an instance of it.
public delegate void ScrollDelegate();
private ScrollDelegate s_del;
   The next step is to initialize it in the Form_Load method.
s_del = new ScrollDelegate(ScrollText);
    Now, when we call the BeginInvoke() method of s_del, the scrolling will occur. We win callBeginInvoke() in the btn_start_Click method, replacing the call to ScrollText method.
s_del.BeginInvoke(null,null);
    Let's run the application again now. You notice how improvement we've created by adding 4 lines of code?
   Here is the application when I run it on my computer:


   You can play around with the sleep interval(make the interval smaller to have a faster and smoother scroll, and make it bigger to have a "lazy" scroll).
   Well, we've reached the end of this lesson. I hope you had as much fun as I did!

Attachments:

   Project Files: TextScroll.zip

Creating Custom Windows(C#)


Introduction

          This article introduces you to creating your own custom appearance user interfaces, witch you will find to be much more easy then you've ever expected. The code for this article is written in C#, and for it to work on your machine, you must have .NET Framework 1.1 installed.

Getting to work

           Enough talking already, let's get to work. First of all, you will need some custom graphics. In the sample attached, you will find some jpegs, but you can make your own using any picture editor, from Paint to Photoshop. The picture I've attached might not be pretty enough, but they'll do the job just fine.
           Now, using Visual Studio, let's create a new C# Windows Application. To do that, go to:File -> New -> Project -> Visual C# Projects -> Windows Application. Choose a name for your project, and press OK (you might also want to place your project in a different folder then the default one, so change the location of your project if you need to). If you've done this right, you are now in front of a plain window, with nothing on it. We must first create the design of the application, and then later we'll do the coding. From the main menu, choose View -> Properties Window (or just press F4).
          In the properties window, we have to change some of the default settings. First, we must set the FormBorderStyle property to None. I've also set the TopMost property to True, but that's not really necessary(by setting it to true, the application would stay on top of other windows, even if it doesn't have the focus).




          The next step is to add the title bar. To do that, select from the main menu View -> ToolBox (or press Ctrl+Alt+X). We need to add a PictureBox control, so find and drag it to the form's surface. We need to resize it and position it like it's done in the picture below:


          Before adjusting the PictureBox, we must add the pictures. To do that, we select View -> Solution Explorer(Ctrl+Alt+L), right-click the project name, choose Add -> New Folder. Name the folder Images or any other name you like. Now, right-click the folder we had just created, choose Add -> Add Existing Item…, browse to the pictures you want to use and select them, press OK and there are included in our project. The next thing we need to do is select thePictureBox and adjust its properties. We have to set the Image property to the image we want to use, that we previously added. One more property needs to be changed, the Dock property changed to Top. We now need to add another PictureBox, for the close button. Position the newly created PictureBox on the upper right corner of the form, and set its Image property to the image you want (the image I used is called "close normal.jpg" and it's included in the graphics folder).
          We are done with the design part. Now let's get to the coding part. The first thing we need to do is put some code to have the ability to close the window. To do that, double-click the second PictureBox, and Visual Studio will create the following method:

private void pictureBox2_Click_1(object sender, System.EventArgs e)
{

}
So, we need to tell the form that when that picture box is clicked, it must close. We need to add the following code:
this.Close();
           The application is ready to run for the first time. To run it, we must choose Debug -> Start Without Debugging (or simply press Ctrl+F5).



          For the final part of this tutorial, let's add functionality to the form by allowing the user to move it. To do that, we must handle events for the MouseDownMouseMove and MouseUpactions. In the Designer View, select the first PictureBox, the bigger one, and go to theProperties window (or press F4), and click the lightning shaped button. In the Mouse section, double-click MouseDown property. Visual Studio has created for you a function to handle theMouseDown action on the PictureBox (NOT on the form):
private void pictureBox1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
}
          We'll need to declare a variable to see weather the mouse is pressed or not (I called itmouse_is_down, you can call it however you want). We must declare this variable, after the class definition, right under the declaration of the two PictureBox controls. Add the following code:
private bool mouse_is_down=false;
          Now, go to pictureBox1_MouseDown method and add the following:
mouse_is_down=true;
          We now know when the mouse is down. But if the user presses the mouse and then releases it, our mouse_is_down remains true. Let's fix that by adding another function that handles the MouseUp event. In the Mouse section, double-click MouseUp property, and add the following code:
mouse_is_down=false;
          So far, so good. Let's handle now the MouseMove action. Double-click the MouseMoveaction. We are now in the pictureBox1_MouseMove method. If the mouse is down, and the user wants to move the window, we would like that to move around. Add the following code:
if ( mouse_is_down )
{
Point current_pos = Control.MousePosition;
this.Location = current_pos;
}
          The variable of type Point represents the current position of the mouse.
Let's run the application and see what's happening.

          As you can see, the window moves, but the mouse position is set to the upper left corner of the window. Why is that? By changing the mouse position, we also change the window position and the mouse coordinates are set to (0,0)(relative to the window) . This can be avoided by adding some extra code. All we have to do is remember the position of the mouse when the click was performed. We'll need to declare another variable, of type Point, at the beginning of the class. I called it mouse_pos.
private Point mouse_pos;
          In the pictureBox1_MouseDown method, add the following code to remember the mouse position when the click was performed:
mouse_pos.X = e.X;
mouse_pos.Y = e.Y;
Let's go now to the pictureBox1_MouseMove method, and add:
if ( mouse_is_down )
{
Point current_pos = Control.MousePosition;
current_pos.X = current_pos.X - mouse_pos.X; //add this current_pos.Y = current_pos.Y - mouse_pos.Y; //add this
this.Location = current_pos;
}
We now added code to remember the mouse position. Run the application.
          In the end, for some fun, let's add some improvements:
- in the pictureBox1_MouseDown method, add the following line:
pictureBox1.Image=new Bitmap("..\\..\\Images\\up bar selected.jpg");
What this basically does is when you perform the click, changes the Image property ofpictureBox1.
- in the PictureBox_MouseUp method, let's change back the image:
pictureBox1.Image =new Bitmap("..\\..\\Images\\up bar.jpg");
Note: the ".." indicates the current directory's parent directory, "\" indicates an escape sequence, and must be typed twice("\\") to indicate the "\" character. When you run your application, your current directory is "{path to application}\bin\Debug", and to access the Image folder, I have to "climb" two directories up. Let's play some more. Set the form's BackgroundImage property to the "face.jpg" image located in the Images folder. Also, set TransparencyKey toGray(128,128,128) (You may need to set your color depth to 16 bits to see the effects. This is a bug from Microsoft.)

Here is the final application:



Well, here's where this ends. Hope you had as much fun as me doing this.
I wish you good luck and happy programming!

Attachments:

   Project Files: Custom_Window_Sample.zip

Simple Calculator Program using C#.net(code)

Description

This is a simple calculator program that was written using Visual Studio.NET and C#.  The calculator is a good program to learn how to use mouse and keyboard events. To use this code, create a new C# Windows Application project and  paste this code in.

Source Code:
// Source Code starts
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace Calculator1
{
/// 
/// This is a simple calculator program.
/// Author: David Kulbok
/// Date: 10/16/01
/// Email: dkulbok2@yahoo.com
/// 
/// This is my first venture into C# so some of the techniques might seem quick and dirty.
/// If there is a more efficient way of doing something (i.e. Making sure that hitting Enter 
/// fires doEquals()) please let me know. I hope that you will learn as much from this 
/// program as I did about C# controls and events.
/// 
/// David Kulbok
/// 
/// 

public class Calculator1 : System.Windows.Forms.Form
{
#region Constructor
public Calculator1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
#endregion
#region
 Global Variables
private System.Windows.Forms.Button btnAdd;
public System.Windows.Forms.TextBox txtResult;
private System.Windows.Forms.Button btn1;
private System.Windows.Forms.Button btn2;
private System.Windows.Forms.Button btn3;
private System.Windows.Forms.Button btn4;
private System.Windows.Forms.Button btn5;
private System.Windows.Forms.Button btn6;
private System.Windows.Forms.Button btn7;
private System.Windows.Forms.Button btn8;
private System.Windows.Forms.Button btn9;
private System.Windows.Forms.Button btn0;
private System.Windows.Forms.Button btnSubtract;
private System.Windows.Forms.Button btnMultiply;
private System.Windows.Forms.Button btnDivide;
private System.Windows.Forms.Button btnEquals;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnNegative;
private System.Windows.Forms.Button btnDecimal;
/// 
/// Required designer variable.
/// 

private System.ComponentModel.Container components = null;
/// 
/// These are global variables defined for use in the calculator
/// 
private int opMain = 0; /// Stores the value of the operation (1-4)
private double mainNum1 = 0; ///Stores the value of the first number
private double mainNum2 = 0; ///Stores the value of the second number
private bool isSecond = false; //Boolean value used to determine if input is the second or first number.
private bool isDone = false; ///Boolean value used to determine if the equals key was pressed.
private bool isDecimal = false; //Boolean value used to determine if there is a decimal in the number.
#endregion
#region
 Dispose
/// 
/// Clean up any resources being used.
/// 

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion 
#region Windows Form Designer generated code
/// 
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// Most of these just set the controls and the properties for them. There are some event handlers that I will explain as I go along.
/// 
private void InitializeComponent()
{
this.btn2 = new System.Windows.Forms.Button();
this.btn3 = new System.Windows.Forms.Button();
this.btn0 = new System.Windows.Forms.Button();
this.btn1 = new System.Windows.Forms.Button();
this.btn6 = new System.Windows.Forms.Button();
this.btn7 = new System.Windows.Forms.Button();
this.btn4 = new System.Windows.Forms.Button();
this.btnDivide = new System.Windows.Forms.Button();
this.btn9 = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnSubtract = new System.Windows.Forms.Button();
this.btnDecimal = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.txtResult = new System.Windows.Forms.TextBox();
this.btnMultiply = new System.Windows.Forms.Button();
this.btn5 = new System.Windows.Forms.Button();
this.btn8 = new System.Windows.Forms.Button();
this.btnEquals = new System.Windows.Forms.Button();
this.btnNegative = new System.Windows.Forms.Button();
this.SuspendLayout();
// 
// btn2
// 
this.btn2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn2.Location = new System.Drawing.Point(48, 40);
this.btn2.Name = "btn2";
this.btn2.Size = new System.Drawing.Size(32, 32);
this.btn2.TabIndex = 13;
this.btn2.TabStop = false;
this.btn2.Text = "2";
this.btn2.Click += new System.EventHandler(this.btn2_Click);
//
// btn3
//
this.btn3.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn3.Location = new System.Drawing.Point(88, 40);
this.btn3.Name = "btn3";
this.btn3.Size = new System.Drawing.Size(32, 32);
this.btn3.TabIndex = 12;
this.btn3.TabStop = false;
this.btn3.Text = "3";
this.btn3.Click += new System.EventHandler(this.btn3_Click);
//
// btn0
//
this.btn0.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)), ((System.Byte)(192)));
this.btn0.Location = new System.Drawing.Point(48, 160);
this.btn0.Name = "btn0";
this.btn0.Size = new System.Drawing.Size(32, 32);
this.btn0.TabIndex = 5;
this.btn0.TabStop = false;
this.btn0.Text = "0";
this.btn0.Click += new System.EventHandler(this.btn0_Click);
//
// btn1
//
this.btn1.ForeColor = ystem.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn1.Location = new System.Drawing.Point(8, 40);
this.btn1.Name = "btn1";
this.btn1.Size = new System.Drawing.Size(32, 32);
this.btn1.TabIndex = 14;
this.btn1.TabStop = false;
this.btn1.Text = "1";
this.btn1.Click += new System.EventHandler(this.btn1_Click_1);
//
// btn6
//
this.btn6.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn6.Location = new System.Drawing.Point(88, 80);
this.btn6.Name = "btn6";
this.btn6.Size = new System.Drawing.Size(32, 32);
this.btn6.TabIndex = 9;
this.btn6.TabStop = false;
this.btn6.Text = "6";
this.btn6.Click += new System.EventHandler(this.btn6_Click);
//
//btn7
// 
this.btn7.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn7.Location = new System.Drawing.Point(8, 120);
this.btn7.Name = "btn7";
this.btn7.Size = new System.Drawing.Size(32, 32);
this.btn7.TabIndex = 8;
this.btn7.TabStop = false;
this.btn7.Text = "7";
this.btn7.Click += new System.EventHandler(this.btn7_Click);
//
// btn4
//
this.btn4.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn4.Location = new System.Drawing.Point(8, 80);
this.btn4.Name = "btn4";
this.btn4.Size = new System.Drawing.Size(32, 32);
this.btn4.TabIndex = 11;
this.btn4.TabStop = false;
this.btn4.Text = "4";
this.btn4.Click += new System.EventHandler(this.btn4_Click);
//
// btnDivide
//
this.btnDivide.Location = new System.Drawing.Point(136, 160);
this.btnDivide.Name = "btnDivide";
this.btnDivide.Size = new System.Drawing.Size(32, 32);
this.btnDivide.TabIndex = 2;
this.btnDivide.TabStop = false;
this.btnDivide.Text = "/";
this.btnDivide.Click += new System.EventHandler(this.btnDivide_Click);
//
// btn9
//
this.btn9.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn9.Location = new System.Drawing.Point(88, 120);
this.btn9.Name = "btn9";
this.btn9.Size = new System.Drawing.Size(32, 32);
this.btn9.TabIndex = 6;
this.btn9.TabStop = false;
this.btn9.Text = "9";
this.btn9.Click += new System.EventHandler(this.btn9_Click);
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(136, 40);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(32, 32);
this.btnAdd.TabIndex = 15;
this.btnAdd.TabStop = false;
this.btnAdd.Text = "+";
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnSubtract
//
this.btnSubtract.Location = new System.Drawing.Point(136, 80);
this.btnSubtract.Name = "btnSubtract";
this.btnSubtract.Size = new System.Drawing.Size(32, 32);
this.btnSubtract.TabIndex = 4;
this.btnSubtract.TabStop = false;
this.btnSubtract.Text = "-";
this.btnSubtract.Click += new System.EventHandler(this.btnSubtract_Click);
//
// btnDecimal
//
this.btnDecimal.Location = new System.Drawing.Point(88, 200);
this.btnDecimal.Name = "btnDecimal";
this.btnDecimal.Size = new System.Drawing.Size(32, 32);
this.btnDecimal.TabIndex = 17;
this.btnDecimal.TabStop = false;
this.btnDecimal.Text = ".";
this.btnDecimal.Click += new System.EventHandler(this.btnDecimal_Click);
//
// btnClear
//
this.btnClear.ForeColor = System.Drawing.Color.Red;
this.btnClear.Location = new System.Drawing.Point(8, 200);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(32, 32);
this.btnClear.TabIndex = 0;
this.btnClear.TabStop = false;
this.btnClear.Text = "C";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// txtResult
//
this.txtResult.Location = new System.Drawing.Point(8, 8);
this.txtResult.Name = "txtResult";
this.txtResult.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtResult.Size = new System.Drawing.Size(160, 20);
this.txtResult.TabIndex = 15;
this.txtResult.TabStop = false;
this.txtResult.Text = "";
this.txtResult.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// btnMultiply
//
this.btnMultiply.Location = new System.Drawing.Point(136, 120);
this.btnMultiply.Name = "btnMultiply";
this.btnMultiply.Size = new System.Drawing.Size(32, 32);
this.btnMultiply.TabIndex = 3;
this.btnMultiply.TabStop = false;
this.btnMultiply.Text = "*";
this.btnMultiply.Click += new System.EventHandler(this.btnMultiply_Click);
//
// btn5
//
this.btn5.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)192)));
this.btn5.Location = new System.Drawing.Point(48, 80);
this.btn5.Name = "btn5";
this.btn5.Size = new System.Drawing.Size(32, 32);
this.btn5.TabIndex = 10;
this.btn5.TabStop = false;
this.btn5.Text = "5";
this.btn5.Click += new System.EventHandler(this.btn5_Click);
//
// btn8
//
this.btn8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(0)),((System.Byte)(0)),((System.Byte)(192)));
this.btn8.Location = new System.Drawing.Point(48, 120);
this.btn8.Name = "btn8";
this.btn8.Size = new System.Drawing.Size(32, 32);
this.btn8.TabIndex = 7;
this.btn8.TabStop = false;
this.btn8.Text = "8";
this.btn8.Click += new System.EventHandler(this.btn8_Click);
//
// btnEquals
//
this.btnEquals.Location = new System.Drawing.Point(136, 200);
this.btnEquals.Name = "btnEquals";
this.btnEquals.Size = new System.Drawing.Size(32, 32);
this.btnEquals.TabIndex = 1;
this.btnEquals.TabStop = false;
this.btnEquals.Text = "=";
this.btnEquals.Click += new System.EventHandler(this.btnEquals_Click);
//
// btnNegative
//
this.btnNegative.Location = new System.Drawing.Point(48, 200);
this.btnNegative.Name = "btnNegative";
this.btnNegative.Size = new System.Drawing.Size(32, 32);
this.btnNegative.TabIndex = 16;
this.btnNegative.TabStop = false;
this.btnNegative.Text = "+/-";
this.btnNegative.Click += new System.EventHandler(this.btnNegative_Click);
//
// Calculator1
//
this.AcceptButton = this.btnEquals;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 245);
this.Controls.AddRange(new System.Windows.Forms.Control[] 
{this.btnDecimal,
this.btnNegative,
this.btnClear,
this.btnEquals,
this.btnDivide,
this.btnMultiply,
this.btnSubtract,
this.btn0,
this.btn9,
this.btn8,
this.btn7,
this.btn6,
this.btn5,
this.btn4,
this.btn3,
this.btn2,
this.btn1,
this.txtResult,
this.btnAdd});
this.KeyPreview = true;
this.Name = "Calculator1";
this.Text = "Calculator";
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Btn_KeyDown);
this.ResumeLayout(false);
}
#endregion
///Custom Methods
#region setText(String textset)
/// 
/// This method is used to set the text in the textbox to the number entered by the user.
/// 
/// 


public void setText(String textset)
{
if(textset.Equals("clear"))
//If the user hits the clear button
txtResult.Text = ""; //Clear the text and reset the boolean variables.
isDone = false;
isSecond = false;
isDecimal = false;
}
else
{
if(isSecond) //Determine if the number being entered is the begining of the second number.If it is:
{
txtResult.Text = textset;
//Start the text over and set the first # to what the user enters
isSecond = false; //So Calculator knows to continue the # rather than making a new one.
isDecimal = false;
}
else
{
if(isDone) //isDone lets the program know that the user just hit "=" and if they press another # to start a new number.
{
txtResult.Text = textset;
isDone=false; //Set isDone to false so that the number just started is added on to and a new # is not started.
}
else
txtResult.Text += textset; //Simply add on to the existing #.
}
}
btnEquals.Select(); 
//Set the focus back to the "=" button.
}
#endregion
#region
 Calc(double num1, double num2, int op)
/// 
/// Calc takes the 2 numbers and the operation and calcualtes the answer.
/// 
/// 
/// 
/// 
public void Calc(double num1, double num2, int op)
{
double answer = 0;//Initialize answer to 0;
switch(op) //Determine which operation to perform depending on the value of "op"
{
case1:| answer = num1 + num2;
break;
case 2:
answer = num1 - num2;
break;
case 3:
answer = num1 * num2;
break;
case 4:
answer = num1 / num2;
break;
}
setText(answer.ToString()); //Show the answer in the textbox;
}
#endregion
#region
 doEquals()
/// 
/// This method stores the second number, clears the textbox and calls the Calc method
/// 

private void doEquals()
{
mainNum2 =double.Parse(txtResult.Text);
//Set the value of the second number
setText("clear"); //Clear the textbox
Calc(mainNum1, mainNum2,opMain); //Call the Calc method
isDone = true; //Set isDone to true so that if another # is pressed, the program will begin a new number
}
#endregion
#region
 changeSign()
/// 
/// This method changes the sign of the number. If the number is positive
/// it makes it negative and vice versa.
/// 

private void changeSign()
{
double storNum; //Variable to store value of number
if(txtResult.Text.Length > 0) //If there is a number...
{
storNum = double.Parse(txtResult.Text); //Store its value
storNum *= -1; //multiply by negative 1
txtResult.Text = storNum.ToString(); //put it in the textbox.
}
btnEquals.Select(); //Set focus to "=" button
}
#endregion
#region
 setOperator(int operation) 
/// 
/// The method is used to store the first number and the operation being performed.
/// 
//
private void setOperator(int operation)
{
if(txtResult.Text.Length > 0)//Make sure that the user entered a number
{
opMain = operation; //Store the operation
mainNum1 = double.Parse(txtResult.Text); //Store the value of the first number
isSecond = true; //Let the program know to begin the second number
isDone = false; //If a operator button is pressed before a new number, let the program know to start a new umber.
btnEquals.Select(); //Set the focus to the equals button.
}
}
#endregion
#region
 setDecimal()
/// 
/// This method checks to see if the # has a decimal in it. If not, it
/// puts one in. If it does, no decimal is entered.
/// 

private void setDecimal()
{
if(!isDecimal)//Check for existing decimal
{
setText("."); //Add decimal
isDecimal = true; //Let program know decimal has been added
}
btnEquals.Select(); //Set focus to "=" button
}
#endregion
#region
 KeyBoard Events
/// 
/// This method simply determines which key is being pressed.
/// 

/// 
/// 
protected void Btn_KeyDown (object sender,KeyEventArgs e) 
{ 
//MessageBox.Show(e.KeyValue.ToString());
filterKeys(e.KeyValue);
}
/// 
/// This method accepts the value of the key and calls the corresponding methods.
/// It is pretty self-explanatory.
/// 

/// 
public void filterKeys(int keyCode)
{
switch(keyCode)
{
case 96:
setText("0");
break;
case 97:
setText("1");
break;
case 98:
setText("2");
break;
case 99:
setText("3");
break;
case 100:
setText("4");
break;
case 101:
setText("5");
break;
case 102:
setText("6");
break; 
case 103:
setText("7");
break;
case 104:
setText("8");
break;
case 105:
setText("9");
break;
case 67:
setText("clear");
break;
case 107:
setOperator(1);
break;
case 109:
setOperator(2);
break;
case 106:
setOperator(3);
break;
case 111:
setOperator(4);
break;
case 110:
setDecimal();
break;
}
}
#endregion
#region
 Button Functions
///These methods do the same as when a key is pressed except the respond to the 
///mouse clicks on the different controls. These are the methods that were mapped to 
///the controls up top.
private void btnAdd_Click(object sender,System.EventArgs e)
{
setOperator(1);
}
private void btn1_Click_1(object sender,System.EventArgs e)
{
setText("1");
}
private void btn2_Click(object sender,System.EventArgs e)
{
setText("2");
}
private void btn3_Click(object sender,System.EventArgs e)
{
setText("3");
}
private void btn4_Click(object sender,System.EventArgs e)
{
setText("4");
}
private void btn5_Click(object sender,System.EventArgs e)
{
setText("5");
}
private void btn6_Click(object sender,System.EventArgs e)
{
setText("6");
}
private void btn7_Click(object sender,System.EventArgs e)
{
setText("7");
}
private void btn8_Click(object sender,System.EventArgs e)
{
setText("8");
}
private void btn9_Click(object sender,System.EventArgs e)
{
setText("9");
}
private void btn0_Click(object sender,System.EventArgs e)
{
setText("0");
}
private void btnEquals_Click(object sender,System.EventArgs e)
{
doEquals();
}
private void btnClear_Click(object sender,System.EventArgs e)
{
isSecond = false;
setText("clear");
}
private void btnSubtract_Click(object sender,System.EventArgs e)
{
setOperator(2);
}
private void btnMultiply_Click(object sender,System.EventArgs e)
{
setOperator(3);
}
private void btnDivide_Click(object sender,System.EventArgs e)
{
setOperator(4);
}
private void btnNegative_Click(object sender,System.EventArgs e)
{
changeSign();
}
private void btnDecimal_Click(object sender,System.EventArgs e)
{
setDecimal();
}
#endregion
#region
 Main()
/// 
/// The main entry point for the application.
/// 

[STAThread]
static void Main()
deApplication.Run(new Calculator1());
}
#endregion
}nevermind
}
// Source Code End