Windows Applications in Microsoft Visual C++ Studio.NET 2003-2008

by Jim Krumm

|Home| |Computer Science| |Casper College| |Java Source Code| |C++ Source Code| |Visual C++.NET| |Visual Basic| |Assembly Source Code| |Linux| |Dice Program|

|Wyoming| |Casper Area| |American Album| |Personal Album| |Hawaii| |Denmark| |Greece| |Paris| |London| |Amsterdam| |Links| |Sitemap|

Click here to go to the Computer Science Department Home Page for Casper College at www.caspercomsci.com. 


Below are some windows based applications written in C++ in our MFC class (COSC2405).  Conversion from Studio.Net 2003 to Studio.Net 2005 to Studio.Net 2008 and back can be challenging. Some of the biggest differences deal with strings, the declaration of global variables (particularly global strings), when saving to file, asynchronous keys, and working with databases. In Studio 2003 a string declared String *mystring would be declared in Studio 2005 as String ^mystring. Concatenating strings in Studio.NET 2005 is a snap using "+" between multiple strings. This replaces Studio.NET's 2003's "Concat" method. In Studio.NET 2003 concatenating "something" to "somethingElse" and storing the result in strCat was written: strCat = strCat->Concat(something,"   ",somethingElse). Studio.NET 2005 does a much better job than Studio.NET 2003 with rewriting code after controls have been removed from a project. In the past, removing a control, like a button, from a compiled program often left you with a program that wouldn't compile. Studio.NET 2005 is also much quicker compiling than Studio.NET 2003 in both the debug and non-debug mode. Code which used to take minutes compiling on a 1 GHz processor now takes seconds.

Source Code Examples of Windows Applications Written in C++ Studio.NET 2005:

 Here a series of programs and tutorials that show how to write windows applications in C++ in the Studio.NET 2005 environment.

Tutorial 1: Simple Intro on Setting up a Project and Using Basic Controls

Tutorial 2: Windows Basic Form Controls in C++ and Their Properties

Tutorial 3: Windows Forms and Useful ListBox Properties

Tutorial 4: Simple Animation, Which Shows the Use of the Timer and Location Commands

Tutorial 5: Menus

Tutorial 6: File Saving, Opening and Using Common Dialog Boxes

Tutorial 7: Concatenating Strings Together in the Windows C++ Environment:

Tutorial 8: Detecting Asynchronous Keys

Tutorial 9: Using Arrays of Strings

Tutorial 10: Setting up an Access DataBase with a Windows C++ Application

Tutorial 11: Visual AddressBook using an Access Database and XML

Tutorial 12: Making A Setup or Deployment Package of a Microsoft Windows  Program in C++

Tutorial 13: Pong as Visual Studio.Net 2005 C++ Program


Tutorial 1 : Simple Intro on Setting up a Project and Using Basic Controls

        This project will create a simple VB like interface using Windows C++ application in Microsoft Studio.NET 2005 which  transfers text from a TextBox to a Label at the click of a button.  First set up the project by going to :

       File > New > Project  > Visual C++ Projects  > Windows Forms Application

       Then click browse and navigate to the folder to where you want to put your application and then click OK.  Name your project something simple like myInterface.  Go to the toolbox and add a button, a textbox and a label to your form, and make your form look something like this: 

Basic Controls in a Visual C++ Application

        To Change the caption on the button click on the button, and go to the buttons Property Window and select caption and type “Press Me”.   Next double click on the button which will bring up the code window.     Add the one line of code between the brace below to the buton1_Click function:  

private: System::Void button1_Click(System::Object *  sender,  

         System::EventArgs *  e)

{

       label1->Text=textBox1->Text;

}

        Notice the code you add is almost identical to what would be added in Studio.NET Visual Basic, except an arrow is used instead of  a period and the usual C++ semicolon.

(Back) 


Tutorial 2: Windows Basic Form Controls in C++ and Their Properties

        This program will show how to transfer an image to a pictureBox and do conversions from Strings to numerical values and numbers to String. It also shows how to declare Strings in this environment. Set up a form that looks like this:    

Basic Controls in a Microsoft Visual C++ Program

        Then within your project add a file called " HEAD1.jpg" to your debug folder and then add the following lines of code to the appropriate buttons functions:

Code the button following as followings:

private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)

     {               

                       textBox1->Text="hi";

      }

      private: System::Void label1_Click(System::Object *  sender, System::EventArgs *  e)

      {

      }

      private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)

      {

                         label1->Text=textBox1->Text;

      }

      private: System::Void button3_Click(System::Object *  sender, System::EventArgs *  e)

     {                                    pictureBox1->Image=Image::FromFile("HEAD1.jpg");

    }

private: System::Void button4_Click(System::Object *  sender, System::EventArgs *  e)

   {

                   int num1;

                   int num2;

                   int answer;

                   String ^strNum1;

                   String ^strNum2;

                   String ^strAnswer;

                   strNum1=textBox2->Text;

                   strNum2=textBox3->Text;

                   num1=Int32::Parse(strNum1);

                   num2=Int32::Parse(strNum2);

                   answer=num1+num2;

                   strAnswer=answer.ToString();

                  label4->Text=strAnswer;

      }

(Back) 


Tutorial 3 : Windows Forms and Useful ListBox Properties    

      This program will show how to use listboxes, and some of their more useful properties. First create a form which looks as follows, including the one listBox shown:

Listboxes in a Visual Microsoft C++ Program

      Code the buttons as followings:

private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)

                   {

                         listBox1->Items ->Add(textBox1->Text );

                         textBox1->Text="";

                   }

      private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)

        {

         int numListBoxItems;

         numListBoxItems=listBox1->Items ->Count;

         label3->Text=numListBoxItems.ToString() ;

         }

private: System::Void button3_Click(System::Object *  sender, System::EventArgs *  e)

             {

                   int position;

                   String ^myString;

                   myString=textBox2->Text;

                   position=listBox1->Items->IndexOf(myString);

                   label4->Text=position.ToString();

             }

private: System::Void button4_Click(System::Object *  sender, System::EventArgs *  e)

             {

                   String ^newWord;

                   int position;

                   newWord=textBox3->Text;

                   position=Int32::Parse(textBox4->Text);

                   listBox1->Items->Insert(position, newWord);

             }

private: System::Void button5_Click(System::Object *  sender, System::EventArgs *  e)

             {

                   listBox1->Sorted=true;//(true);

             }

private: System::Void button6_Click(System::Object *  sender, System::EventArgs *  e)

             {

                   String ^myString;

                   myString=textBox5->Text;

                   listBox1->Items->Remove(myString);

             }

private: System::Void button7_Click(System::Object *  sender, System::EventArgs *  e)

             {

                   int position;

                   String ^myString;

                   myString=textBox6->Text;

                   position=Int32::Parse(myString);

                   listBox1->Items->RemoveAt(position);

             }

      Note: If you lose the design window (which often happens when you open the “sln”  file using explorer) try the following: 

      Go to File > New > Project  > Window Form Application

       To make a design window appear which shows the forms go to view > designer

(Back) 


Tutorial 4: Simple Animation, Which Shows the Use of the Timer and Location Commands

       This tutorial will show how to move a control button around the form employing the timer.  It also shows something about how placement works and the coordinate system of the form. Begin by designing a form which looks as follows:       

Basic animation with timers in a Microsoft Visual C++ Program

Set the timer's enabled property to false. Then code the following to the buttons:

private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)

                   {

                         button1->Visible=false;

                         button2->Visible=true;

                         timer1->Enabled=true;

                         timer1->Interval=30;

                   }

      private: System::Void button2_Click(System::Object *  sender, System::EventArgs *  e)

                   {

                         timer1->Enabled=false;

                         button1->Visible=true;

                   }

      private: System::Void timer1_Tick(System::Object *  sender, System::EventArgs *  e)

                   {

                         static bool NE, NW, SW, SE;

                         static x, y;

                         //label1->Text=SE.ToString();

                         label1->Text=x.ToString();                         

      if (NE == false && NW == false && SW == false && SE== false)

                         {

                               x=8;

                               y=64;

                               SE=true;

                         }

                         if (NE)

                         {

                               x=x+4;

                               y=y-4;

                               if (x>=220)

                               {

                                     SW=false;

                                     NE=false;

                                     NW=true;

                                     SE=false;

                               }

                               if (y<=0)

                               {

                                     SW=false;

                                     NE=false;

                                     NW=false;

                                     SE=true;

                               }

                         }

                         //*********************

                         if (SE)

                         {

                               x=x+4;

                               y=y+4;

                               if (x>=220)

                               {

                                     SW=true;

                                     NE=false;

                                     NW=false;

                                     SE=false;

                               }

                               if (y>=250)

                               {

                                     SW=false;

                                     NE=true;

                                     NW=false;

                                     SE=false;

                               }

                         }

                         //**********************

                         if (SW)

                         {

                               x=x-4;

                               y=y+4;

                               if (x<=0)

                               {

                                     SW=false;

                                     NE=false;

                                     NW=false;

                                     SE=true;

                               }

                               if (y>=250)

                               {

                                     SW=false;

                                     NE=false;

                                     NW=true;

                                     SE=false;

                               }

                         }

                         //************************

                         if (NW)

                         {

                               x=x-4;

                               y=y-4;

                               if (x<=0)

                               {

                                     SW=false;

                                     NE=true;

                                     NW=false;

                                     SE=false;

                               }

                               if (y<=0)

                               {

                                     SW=true;

                                     NE=false;

                                     NW=false;

                                     SE=false;

                               }

                         }                     

               button2->Location=System::Drawing::Point(x,y);           

      }

   (Back) 


Tutorial 5 : Menus

        In this tutorial you will add a Menu to make button and textbox appear.  To add a menu to your form go to the toolBox and double Click on the the mainMenu tool. This will add a menu to your form. Then type "&File" where it says "Type Here", which add File to the Menu. Then in the box below "File" type "Make Button Appear" and then "Make TextBox Appear", then a lone hyphen (-), and then E&xit. Then add the remaining items to your menu until it looks something like this:   

Menus and Visibility

        Then add the following code to the appropriate item in the menu by double clicking on this item to get to its Code Window:

private: System::Void menuItem2_Click(System::Object *  sender, System::EventArgs *  e)

                   {

                    button1->Visible=true;

                   }

private: System::Void menuItem3_Click(System::Object *  sender, System::EventArgs *  e)

             {

               textBox1->Visible=true;

             }

private: System::Void menuItem5_Click(System::Object *  sender, System::EventArgs *  e)

             {                                                  

              System::Environment::Exit(System::Environment::ExitCode);

             }

private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)

             {

          }

(Back) 


Tutorial 6 : File Saving, Opening and Using Common Dialog Boxes

        This program will show you how to save to file, open from file and how to use dialog boxes to perform these tasks. Begin by placing a text file call "myfile.txt" in your debug directory with a few lines of text placed in it of your choosing. Then design a form which looks as follow:    

File Opening and Saving Common Dialog Boxes

        Add to the namespace region:

    using namespace System::IO;

        Add the following code to the relevant buttons: 

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

       {                        

         try

       {

        FileStream ^fileInput = gcnew FileStream("myfile.txt", FileMode::OpenOrCreate,     FileAccess::ReadWrite);

        StreamReader ^streamIn = gcnew StreamReader(fileInput);

        while(!streamIn->EndOfStream)

         {

          listBox1->Items->Add(streamIn->ReadLine());

         };    

         streamIn->Close();

         }

          catch(IOException ^)

          {

          }

           }           

       private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

          {

            try

           {

           FileStream ^outFile = gcnew FileStream("mynewfile.txt", FileMode::Create, FileAccess::Write);

           StreamWriter ^streamOut = gcnew StreamWriter(outFile);

    streamOut->WriteLine(textBox1->Text);                              

                streamOut->Close();

                 }

                 catch(IOException ^)

                 {

                 }

              }

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {

                   String ^myfile = "";

                      openFileDialog1->ShowDialog() ;

                      myfile = openFileDialog1->FileName;

                      try

                           {

                                  FileStream ^fileInput = gcnew FileStream(myfile, FileMode::OpenOrCreate, FileAccess::ReadWrite);

                                  StreamReader ^streamIn = gcnew StreamReader(fileInput);

                                  while(!streamIn->EndOfStream)

                                  {

                                         listBox1->Items->Add(streamIn->ReadLine());

                                  };    

                                  streamIn->Close();

                           }

                         catch(IOException ^)

                         {

                         }

               }

private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e)

               {

                      String ^myfile = "";

                      saveFileDialog1->ShowDialog() ;

                      myfile = saveFileDialog1->FileName;

                try

                      {

                            FileStream ^outFile = gcnew FileStream(myfile, FileMode::Create, FileAccess::Write);

             StreamWriter ^streamOut = gcnew StreamWriter(outFile);

             streamOut->WriteLine(textBox1->Text);                              

                            streamOut->Close();

                      }

                      catch(IOException ^)

                      {

                      }           

               }

private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e)

               {

                        try

                      {

                            FileStream ^outFile = gcnew FileStream("myfile.txt", FileMode::Append, FileAccess::Write);

              StreamWriter ^streamOut = gcnew StreamWriter(outFile);

                                   streamOut->WriteLine(textBox1->Text);                              

                       streamOut->Close();

                      }

                      catch(IOException ^)

                      {

                      }

               }

};

(Back) 


Tutorial 7: Concatenating Strings Together in the Windows C++ Environment:

        This program will show how to put two strings together to create a combination of the two. This is called concatenation.  Make your form look something like this:   

Concatenating strings in Visual Microsoft Programs

Add the following code to the button: 

private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)

      {

       String ^strCat;

       String ^something=textBox1->Text;

       String ^somethingElse=textBox2->Text;

       strCat=something+"   "+somethingElse;

       listBox1->Items->Add(strCat)

      }

(Back) 


Tutorial 8 : Detecting Asynchronous Keys

        This project will allow you to move a label around your form using Asynchronous Keys.   It is called asynchronous because more than one key can be pressed at a time and it will be recognized. This is usually something that isn't allowed. First set up your form to look as follows (and yes a timer needs to be added). A big change in Studio 2005 (from Studio 2003) is that you must include the dynamic link library user32.dll for this program to allow the asynchronous reading of key presses. 

Asynchronous Key Detection

        Set the timer to be enabled with an interval of 20. These means it goes off every 20/1000 of a second. Next code the following, add everything in yellow: 

#pragma once

namespace anotherKeypressprogram1

{

#include <windows.h>

#include <time.h>

#pragma comment(lib, "user32")

...
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e)

                            if (KEY_DOWN(VK_LEFT))

                                label1->Text="left";

                            if (KEY_DOWN(VK_RIGHT))

                                label1->Text="right";

                            if (KEY_DOWN(VK_UP))

                                label1->Text="up";

                            if (KEY_DOWN(VK_DOWN))

                                label1->Text="down";

                            if (KEY_DOWN(VK_SPACE))                                label1->Text="space";

                            if (KEY_DOWN(VK_ESCAPE))

                                label1->Text="escape";

                            if (KEY_DOWN(65))

                                label1->Text="A";

                            if (KEY_DOWN(90))

                                label1->Text="Z";

                      }

       };

}

(Back) 


Tutorial 9: Using Arrays of Strings

        In this tutorial you will see how to create arrays of strings. Make a form which looks as follows:

Arrays of Strings

public ref class Form1 : public System::Windows::Forms::Form

      {

      public:

            static array<String^>^ first = gcnew array<String^>(100);

            static array<String^>^ last = gcnew array<String^>(100);

            static int i=0;

            Form1(void)

                     . . .

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

             {                            

                   first[i]=textBox1->Text;

                   last[i]=textBox2->Text;

                   listBox1->Items->Add(first[i]);

                   listBox1->Items->Add(last[i]);

                   textBox1->Text="";

                   textBox2->Text="";

                   textBox1->Focus();

                   i++;            

             }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

             {          

                   int index=Int32::Parse(textBox3->Text);

                   if(index>=0 && index <i)

                   {

                         textBox1->Text=first[index];

                       textBox2->Text=last[index];

                   }

                   else

                   {

                         textBox1->Text="";

                         textBox2->Text="";

                         MessageBox::Show("Index Out of Range");

                         textBox3->Focus();

                   }

             }

         };

}

 (Back) 


Tutorial 10: Setting up an Access DataBase with a Windows C++ Application and Two Ways to Insert Data Into a Database

        Click here if you would  like the source code to this file and its database. This program shows how to insert a record into a database using SQL commands and Access 2003. First create a database by entering data called “phonebook.mdb” on the root of your C:\ drive using Access. This should look as follows:

Access Database Image

        When you finish entering your data go to file and save the table as Table1 (the default).  Say yes to creating a primary field.  Since it matters where you put your database, it is easiest to put it in the root of your C:\ drive after you have created it.  Also be careful,  databases may be case sensitive.  Close Access and your database before going on!

        Start a project.  Add a DataGridView object to the form from data in the toolbox.  Click on the arrow going to the right in the top right of dataGridView1.

Access Database Image

        Select Choose Data Source

Access Database Image

        and select Add Project Data Source.

Access Database Image

        Select database and click next.

Access Database Image

        Select New Connection.

Access Database Image

        This will trigger the appearance of the following dialog window:

Access Database Image

        Select Change, which will cause the following window to appear and select “Microsoft Access Database File” and then OK.

 Access Database Image

        This will cause you to return to the Add Connection Dialog which looks as follows.  Click browse and navigate to and select phonebook.mdb.    Don’t include a password but leave Admin as shown.  Click on test connection and make sure a connection to the database exists. Then click OK.  Back at the wizard click Next.

Access Database Image

        In the following dialog window select Tables as shown and click Finish. 

Access Database Image

        This should take you back to your original form.  Go the ToolBox and right click in the Data region of the toolbox and select “Choose Items."  

Access Database Image

        Select OleDbDataAdapter and OleDbConnection from the .NET Framework Components by putting check in its box and press OK.  This will add the OleDbDataAdapter and OleDbConnection tools to the toolBar

Access Database Image

        Double click on the OleDbDataAdapter, adding it to your project.  This will trigger the appearance of the Data Adapter Configuration Wizard as shown below. 

Access Database Image

        Click the down arrow below "select which data connection should the data adapter use" and select phonebook.mdb and click next.  In the following dialog window select Use SQL statements. 

Access Database Image

Access Database Image

        In the next window click on Query Builder… 

Access Database Image

        In the next dialog window select Add, then close this “Add Table Window”.  As in the following picture  select All Columns and click on OK.

Access Database Image

        This should lead to the dialog box:

Access Database Image

        Click Advanced options.  Click OK.  Click Finish. 

Access Database Image  

        If something goes wrong in setting up your database, it is very, very difficult to fix.   You may have to go to view, select Server Explorer, right click on the database you just configured and select delete.  Then remove the related objects on your form.  If this doesn’t clean things out so you get the above window you may have to close your project, open a new one and start over.  It may even be necessary to reboot your computer.

Design a form which looks as follows:

Access Database Image

        To the right and below the First, Last, and Phone are Textboxes  textBox1, textBox2, and textBox3.  Below the Insert button is the large multi-lined Textbox textBox4.  In your form's code window add to the using namespace area the line of code:

        using namespace System::Data::OleDb;

        Then add oleDbConnection1->Open() in the following area.

public:

                        Form1(void)

                        {

                                    InitializeComponent();

                                    oleDbConnection1->Open();

                        }

        Next code the following under your insert button (named button1).  This is critical:  every apostrophe, quote, space, word has to be done as follows in the insert SQL call (as everything means something): 

       private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e)

       {                         

          this->Table1TableAdapter->Fill(this->myphonebook4DataSet->Table1);

       }

       private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

       {

               try {

                   if ( !textBox1->Text->Equals( String::Empty ) &&

                          !textBox2->Text->Equals( String::Empty ) &&

                !textBox3->Text->Equals( String::Empty ) ) {

                // create the SQL query to insert a row                     

                           //********************

                 oleDbDataAdapter1->InsertCommand->CommandText =

            "INSERT INTO `Table1` (`Last`, `First`, `Phone`) VALUES ('"+textBox2->Text+"', '"+textBox1->Text+"', '"+ textBox3->Text+"')" ;

                         //**********************

                textBox4->Text="\r\nInserting: "+oleDbDataAdapter1->InsertCommand->CommandText+"\r\n" ;

                // send query

                oleDbDataAdapter1->InsertCommand->ExecuteNonQuery();

                textBox4->Text="\r\nInsert successful\r\n" ;

                } // end if

                else

                  textBox4->Text="\r\nAll fields are required.\r\n" ;

               } // end try

               catch ( OleDbException ^oleException ) {

                  MessageBox::Show( oleException->Message, "Error",

                     MessageBoxButtons::OK, MessageBoxIcon::Error );

               } // end catch

        }

       private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

       {

                        String ^firstName;

                        String ^lastName;

                        String ^phone;

                        firstName=textBox1->Text;

                        lastName=textBox2->Text;

                        phone=textBox3->Text;

                        this->Table1TableAdapter->Insert( lastName, firstName,phone); //does a insert successfully                        this->Table1TableAdapter->Fill(this->phonebookDataSet->Table1);

                        dataGridView1->Refresh();

       }

        In the code above for button 1 the odd angled apostrophes are usually found on the keyboard just below the escape key.  They are supposed to be there as are the straight apostrophes found on the keyboard on the double quotes key.  Help with getting this line correct (particularly with the angled apostrophes) can be found for the properties window of  oleDbDataAdapter1.  In the properties window of oleDbDataAdapter1 under the InsertCommand property you can copy the setting “INSERT INTO `Table1` (`Last`, `First`, `Phone`) VALUES (?, ?, ?)”  and paste this directly into your program.  Then make the necessary changes to this line replacing everything after “VALUES” with ('"+textBox2->Text+"', '"+ textBox1->Text+"', '"+textBox3->Text+"')";  Other key database commands such as delete, update, and select are in the properties window of the oleDbDataAdapter1.

Access Database Image

        The program should work now.  Confirmation will come in textBox4, but you can also check your database to see if your new entry is added.  A word of caution here:  sometimes a database will not allow a write if your database is open in Access.  When the program runs successfully the program should look as follows:

Access Database Image

 (Back)


Tutorial 11 : Visual AddressBook 2005 using an Access Database

        This program uses the automated XML environment to set up a C++ Windows Database application using Microsoft Studio 2005.  This program shows how to insert a record into a database using SQL commands and Access 2003. First create a database by entering data called “phonebook.mdb” on the root of your C:\ drive using Access. This should look as follows:

        When you finish entering your data go to file and save the table as Table1 (the default).  Say yes to creating a primary field.  Since it matters where you put your database, it is easiest to put it in the root of your C:\ drive after you have created it.  Also be careful, databases may be case sensitive.  Close Access and your database before going on!

        Start a project.  Go the ToolBox and right click on the toolbox and select “choose items”.  Select OleDbDataAdapter by putting an x to its left. 

        Again put your application in the root directory.  Put your  database in the root (for simplicity, as the path to the database cannot  change if your application undergoes name changes).  Then make a Visual C++ Windows Application project called AddressBookDB.   From your toolbox draw a  dataGridView on your form.   Within  the DataGridView Tasks window (which can be activated by clicking on the small arrow appearing at the top of the DataGridView field) select  “Choose Data Source.”

        In the next window Click on Add Project Data Source…

        In the Data Source Configuration Wizard, select Database and then next.

        This will trigger the following window:

 

        In this window select New Connection… which will display the following window:

        Here click Change… which will display the following window:

        Here select Microsoft Access Database File, click OK and in the previous window click browse and navigate and select phonebook.mdb.  This will take you back Data Configuration Wizard.  In this wizard click next which will display the following window:

        Here expand and select Tables to select Table1, ID, First, First, Phone, Views.  Then click Finish.  This will take you back to your original form which will look something like the form which follows:

 

        Here size the dataGridView so it displays all the fields (ID through Phone) shown above.  Notice 3 tools have been automatically added to your form:  phonebookDataSet, table1BindingSource, and the TableTableAdapter.  Now go to the main menu as shown below

        and select show Data Sources.  A Data Sources window will appear.  Expand the data sources so that all the data sources (Last, First, Phone) can be seen.  Now drag and drop Last from the Data Sources window to your form.  This will put a label and a textbox on your form tied to the Last field in your database which looks as follows:

        Add the other fields of First, and Phone to your form until your program.  The TextBox for Last will be automatically named: LastTextBox,  for First will be named FirstTextBox, and for Phone will be named PhoneTextBox.   Then add The following buttons to your form as  follows:  Button1 for  First Item, Button2 for  Next Record, Button3 for Last Record, Button4 for Add Record, Button5 for Save Database,  Button6 for Delete Record,  Button7 for  Cancel, Button8 for  Find Record and finally Button8 for Reset Data.

        Next add a groupbox to labeled Find, and to this groupbox add 2 Textboxes and the following labels such that this Groupbox looks as follows.  The textbox in the find groupbox for First is textBox4, and for Last is textBox4, and the label under Phone is label7 with autosize set to false and borderstyle set to fixed3D:

        Next add a picturebox to the right of the find groupbox as follows and load a picture into it.  Put a jpg picture in you code directory of someone to be in your phonebook named in the following fashion:  “first“+“last“+“.jpg” with your cpp files.  For instance a jpg of Alex Einstein would have the name: AlexEinstein.jpg.  Place one picture in directory called Default.jpg and make it an image of whatever you  want a “non-person picture” to look like.  Finally label your form as being the phonebook database program such that the completed  interface looks as follows:

        Go to the code window and add the  following line to the rest of the namespace values:

using namespace System::IO;

        Next write the following code as a function:

void loadPicture()

      {

            String ^FirstN="";

            String ^LastN="";

            String ^filename="";

            FirstN=FirstTextBox->Text;

            LastN=LastTextBox->Text;

            filename=FirstN+LastN+".jpg";

            try{

                 pictureBox1->Image=Image::FromFile(filename);

             }

             catch(IOException ^)

             {

                 pictureBox1->Image=Image::FromFile("default.jpg");

             }

      }

        Finally code the  buttons as follows:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)

                   { //First Item

                       this->Table1TableAdapter->Fill(this->phonebookDataSet->Table1);

                       loadPicture();          

                   }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)

             {    //Next Item

                   this->table1BindingSource->MoveNext();

                   loadPicture();

             }

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e)

             {     //Last Record

                   this->table1BindingSource->MoveLast();

                   loadPicture();

             }

private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e)

             {     //Add Record

                   this->table1BindingSource->AddNew();

                   loadPicture();

             }

private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e)

             {     //Save Database

                   this->Validate();

                   this->table1BindingSource->EndEdit();

                   this->Table1TableAdapter->Update(this->phonebookDataSet->Table1 );

             }

private: System::Void button6_Click(System::Object^  sender, System::EventArgs^  e)

             {     //Delete Record

                   this->table1BindingSource->RemoveCurrent();

             }

private: System::Void button7_Click(System::Object^  sender, System::EventArgs^  e)

             {     //Cancel Edit

                    this->table1BindingSource->CancelEdit();

                   loadPicture();

             }

private: System::Void button8_Click(System::Object^  sender, System::EventArgs^  e)

             {     //Find Record

                   String ^first=FirstTextBox->Text;

                   String ^last=LastTextBox->Text;

                   String ^phone="";

                   try

                   {

                     if (!textBox4->Text->Equals("") && !textBox5->Text->Equals(""))

                     {

                       this->table1BindingSource->Filter="Last='"+textBox5->Text+"' AND "+"First='"+textBox4->Text+"'";

                     }

                     else if (!textBox4->Text->Equals("") )

                     {

                       this->table1BindingSource->Filter="First='"+textBox4->Text+"'";

                     }

                     else if (!textBox5->Text->Equals("") )

                     {

                       this->table1BindingSource->Filter="Last='"+textBox5->Text+"'";

                     }

                     else

                     {}

                   }

                   catch(IOException ^)

                   {

                        pictureBox1->Image=Image::FromFile("default.jpg");

                   }

                     label7->Text=PhoneTextBox->Text; //loads the phone number

                     if (label7->Text->Equals(""))

                         label7->Text="Not Found";

                   loadPicture();

             }

             }

private: System::Void button9_Click(System::Object^  sender, System::EventArgs^  e)

             {

                   this->table1BindingSource->RemoveFilter();

                   this->table1BindingSource->CancelEdit();

                   loadPicture();        

             }

        The finished program looks as follows:

        To add a new record it is necessary to click add record, then enter the data in the Last, First, and Phone fields to the left and then click Save Database.  The First Item, Next Record Last Record buttons allow you to navigate through the database.  To edit, navigate to the person or do a find on them.  Change the fields to the left and then click Save Database.  If you change your mind, Click cancel to cancel  the edit.  To do a find type a first name, or a last name or both into the find fields and click find.  To view all the data in the database again click reset data.

 (Back) 


Tutorial 12 : Making A Setup or Deployment Package of a Microsoft Windows  Program in C++ By Russell Pitts  

        Bring up the project you are working on as a Microsoft Windows Form Application which you wish to distribute.   Here for the sake of simplicity I will use a simple project that has a button on it and a label called “HelloWorld”.  If the button is clicked a message appears in the label that says hello.  It looks as follows: 

        On the button is the simple code:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)                    {

                         label1->Text="Hello!";

                   }

        Rebuild the Project so the project and its files are saved.  Now go to File>New Project>Other Project types>Setup and Deployment>Setup Wizard  as shown in the following figure:

        Under Solution, select “Add to Solution” and then enter OK.    In the setup Wizard, 1 of 5, that follows enter Next...

        In the next window, 2 of 5, go with the default and select Next:

        In the next window, 3 of 5, select Primary output from HelloWorld and Resource Satellite DLL's from HelloWorld and select Finish.

        Open the Solution explorer for the project and right click on Setup1 and select build as is shown in the following figure:

        Navigate in Windows Explorer to the debug folder of Setup1 of your  HelloWorld Project as illustrated in the following figure and copy the entire debug folder

         Then paste the debug folder someplace else and change the name of the debug folder to Setup.  These two files Setup1.msi and setup.exe in this folder are all you need to install the package.

 (Back) 


Tutorial 13: Pong as a Visual Studio.Net 2005 C++ Program    

        Basic Setup:  Make a form of size 476x382.  Right click on the tool box, select choose items, com components, select windows media player.  Add two media players, stay with the default names on everything.  Add the left paddle (pictureBox1), the right paddle (pictureBox2), and the ball (pictureBox3). To start you can make the size of each paddle 10x48 and the ball 20x20.  Position these objects as shown above.  You can use images for the paddles and balls if you wish, or make the backcolor of the paddles black and the ball yellow with a border style of fixed single. Set the sizemode of all 3 objects to stretch image.  Lay a large label on the bottom and  set its backcolor to red.  Size it to 471x37.  Place 4 more labels on the large red label and label them with the defaults above showing the score of player1 and player 2.  Add a mainmenu tool and have it say file.  In its drop down field write speed and exit.  To the right of this menu have music and add a few songs in the fields if you wish.  To the right of this have a help menu (with a single field).  The code goes as follows:

#pragma once

namespace Pong1 {

    #include <windows.h>

    #include <time.h>               //user32.dll-dynamic link library

    #include <mmsystem.h>               //play music/sound effects

    #pragma comment(lib, "user32")

       using namespace System;

       using namespace System::ComponentModel;

       using namespace System::Collections;

       using namespace System::Windows::Forms;

       using namespace System::Data;

       using namespace System::Drawing;

       /// <summary>

       /// Summary for Form1

       ///

       /// WARNING: If you change the name of this class, you will need to change the

       ///          'Resource File Name' property for the managed resource compiler tool

       ///          associated with all .resx files this class depends on.  Otherwise,

       ///          the designers will not be able to interact properly with localized

       ///          resources associated with this form.

       /// </summary>

       public ref class Form1 : public System::Windows::Forms::Form

       {

       public:

              //MACRO

              #define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0 )

        #define KEY_UP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1 )

        static int direction;

              static int xChange=0;

              static int yChange=0;

              static int x=0;

              static int y=0;

       private: AxWMPLib::AxWindowsMediaPlayer^  axWindowsMediaPlayer1;

       private: AxWMPLib::AxWindowsMediaPlayer^  axWindowsMediaPlayer2;

       private: System::Windows::Forms::MenuStrip^  menuStrip1;

       private: System::Windows::Forms::ToolStripMenuItem^  musicToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  airWoldToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  maryHayToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  musicToolStripMenuItem1;

       private: System::Windows::Forms::ToolStripMenuItem^  airWolfToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  maryHayToolStripMenuItem1;

       private: System::Windows::Forms::ToolStripMenuItem^  helpToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  slowToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  mediumToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  fastToolStripMenuItem;

       private: System::Windows::Forms::Label^  label2;

       private: System::Windows::Forms::Label^  label3;

       private: System::Windows::Forms::Label^  label4;

       private: System::Windows::Forms::Label^  label5;

       private: System::Windows::Forms::ToolStripMenuItem^  tresHombresToolStripMenuItem;

       private: System::Windows::Forms::ToolStripMenuItem^  toolStripMenuItem1;

       public:

              static double ballSpeed=1;

              Form1(void)

              {

                     InitializeComponent();

                     //

                     //TODO: Add the constructor code here

                     //

              }

       protected:

              /// <summary>

              /// Clean up any resources being used.

              /// </summary>

              ~Form1()

              {

                     if (components)

                     {

                           delete components;

                     }

              }

       private: System::Windows::Forms::Timer^  timer1;

       private: System::Windows::Forms::PictureBox^  pictureBox1;

       private: System::Windows::Forms::PictureBox^  pictureBox2;

       private: System::Windows::Forms::PictureBox^  pictureBox3;

       private: System::Windows::Forms::Timer^  timer2;

       private: System::Windows::Forms::Label^  label1;

       private: System::ComponentModel::IContainer^  components;

       protected:

       private:

              /// <summary>

              /// Required designer variable.

              /// </summary>

#pragma region Windows Form Designer generated code

              /// <summary>

              /// Required method for Designer support - do not modify

              /// the contents of this method with the code editor.

              /// </summary>

              void InitializeComponent(void)

              {

                     this->components = (gcnew System::ComponentModel::Container());

                     System::ComponentModel::ComponentResourceManager^  resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));

                     this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));

                     this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());

                     this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox());

                     this->pictureBox3 = (gcnew System::Windows::Forms::PictureBox());

                     this->timer2 = (gcnew System::Windows::Forms::Timer(this->components));

                     this->label1 = (gcnew System::Windows::Forms::Label());

                     this->axWindowsMediaPlayer1 = (gcnew AxWMPLib::AxWindowsMediaPlayer());

                     this->axWindowsMediaPlayer2 = (gcnew AxWMPLib::AxWindowsMediaPlayer());

                     this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());

                     this->musicToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->airWoldToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->slowToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->mediumToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->fastToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->maryHayToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->musicToolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->airWolfToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->maryHayToolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->tresHombresToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->helpToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     this->label2 = (gcnew System::Windows::Forms::Label());

                     this->label3 = (gcnew System::Windows::Forms::Label());

                     this->label4 = (gcnew System::Windows::Forms::Label());

                     this->label5 = (gcnew System::Windows::Forms::Label());

                     this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem());

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->BeginInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox2))->BeginInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox3))->BeginInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->axWindowsMediaPlayer1))->BeginInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->axWindowsMediaPlayer2))->BeginInit();

                     this->menuStrip1->SuspendLayout();

                     this->SuspendLayout();

                     //

                     // timer1

                     //

                     this->timer1->Enabled = true;

                     this->timer1->Interval = 25;

                     this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);

                     //

                     // pictureBox1

                     //

                     this->pictureBox1->BackColor = System::Drawing::Color::Black;

                     this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox1.Image")));

                     this->pictureBox1->Location = System::Drawing::Point(12, 163);

                     this->pictureBox1->Name = L"pictureBox1";

                     this->pictureBox1->Size = System::Drawing::Size(30, 48);

                     this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;

                     this->pictureBox1->TabIndex = 0;

                     this->pictureBox1->TabStop = false;

                     //

                     // pictureBox2

                     //

                     this->pictureBox2->BackColor = System::Drawing::Color::Black;

                     this->pictureBox2->Image = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox2.Image")));

                     this->pictureBox2->Location = System::Drawing::Point(426, 163);

                     this->pictureBox2->Name = L"pictureBox2";

                     this->pictureBox2->Size = System::Drawing::Size(30, 48);

                     this->pictureBox2->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;

                     this->pictureBox2->TabIndex = 1;

                     this->pictureBox2->TabStop = false;

                     //

                     // pictureBox3

                     //

                     this->pictureBox3->BackColor = System::Drawing::Color::Yellow;

                     this->pictureBox3->Image = (cli::safe_cast<System::Drawing::Image^  >(resources->GetObject(L"pictureBox3.Image")));

                     this->pictureBox3->Location = System::Drawing::Point(223, 163);

                     this->pictureBox3->Name = L"pictureBox3";

                     this->pictureBox3->Size = System::Drawing::Size(16, 16);

                     this->pictureBox3->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;

                     this->pictureBox3->TabIndex = 2;

                     this->pictureBox3->TabStop = false;

                     this->pictureBox3->Click += gcnew System::EventHandler(this, &Form1::pictureBox3_Click);

                     //

                     // timer2

                     //

                     this->timer2->Interval = 25;

                     this->timer2->Tick += gcnew System::EventHandler(this, &Form1::timer2_Tick);

                     //

                     // label1

                     //

                     this->label1->BackColor = System::Drawing::Color::Red;

                     this->label1->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;

                     this->label1->Location = System::Drawing::Point(3, 312);

                     this->label1->Name = L"label1";

                     this->label1->Size = System::Drawing::Size(471, 37);

                     this->label1->TabIndex = 3;

                     //

                     // axWindowsMediaPlayer1

                     //

                     this->axWindowsMediaPlayer1->Enabled = true;

                     this->axWindowsMediaPlayer1->Location = System::Drawing::Point(204, 91);

                     this->axWindowsMediaPlayer1->Name = L"axWindowsMediaPlayer1";

                     this->axWindowsMediaPlayer1->OcxState = (cli::safe_cast<System::Windows::Forms::AxHost::State^  >(resources->GetObject(L"axWindowsMediaPlayer1.OcxState")));

                     this->axWindowsMediaPlayer1->Size = System::Drawing::Size(75, 23);

                     this->axWindowsMediaPlayer1->TabIndex = 4;

                     this->axWindowsMediaPlayer1->Visible = false;

                     //

                     // axWindowsMediaPlayer2

                     //

                     this->axWindowsMediaPlayer2->Enabled = true;

                     this->axWindowsMediaPlayer2->Location = System::Drawing::Point(204, 134);

                     this->axWindowsMediaPlayer2->Name = L"axWindowsMediaPlayer2";

                     this->axWindowsMediaPlayer2->OcxState = (cli::safe_cast<System::Windows::Forms::AxHost::State^  >(resources->GetObject(L"axWindowsMediaPlayer2.OcxState")));

                     this->axWindowsMediaPlayer2->Size = System::Drawing::Size(75, 23);

                     this->axWindowsMediaPlayer2->TabIndex = 5;

                     this->axWindowsMediaPlayer2->Visible = false;

                     //

                     // menuStrip1

                     //

                     this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^  >(3) {this->musicToolStripMenuItem,

                           this->musicToolStripMenuItem1, this->helpToolStripMenuItem});

                     this->menuStrip1->Location = System::Drawing::Point(0, 0);

                     this->menuStrip1->Name = L"menuStrip1";

                     this->menuStrip1->Size = System::Drawing::Size(468, 24);

                     this->menuStrip1->TabIndex = 6;

                     this->menuStrip1->Text = L"menuStrip1";

                     //

                     // musicToolStripMenuItem

                     //

                     this->musicToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^  >(2) {this->airWoldToolStripMenuItem,

                           this->maryHayToolStripMenuItem});

                     this->musicToolStripMenuItem->Name = L"musicToolStripMenuItem";

                     this->musicToolStripMenuItem->Size = System::Drawing::Size(35, 20);

                     this->musicToolStripMenuItem->Text = L"&File";

                     //

                     // airWoldToolStripMenuItem

                     //

                     this->airWoldToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^  >(3) {this->slowToolStripMenuItem,

                           this->mediumToolStripMenuItem, this->fastToolStripMenuItem});

                     this->airWoldToolStripMenuItem->Name = L"airWoldToolStripMenuItem";

                     this->airWoldToolStripMenuItem->Size = System::Drawing::Size(152, 22);

                     this->airWoldToolStripMenuItem->Text = L"Ball &Speed";

                     this->airWoldToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::airWoldToolStripMenuItem_Click);

                     //

                     // slowToolStripMenuItem

                     //

                     this->slowToolStripMenuItem->Name = L"slowToolStripMenuItem";

                     this->slowToolStripMenuItem->Size = System::Drawing::Size(121, 22);

                     this->slowToolStripMenuItem->Text = L"Slow";

                     this->slowToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::slowToolStripMenuItem_Click);

                     //

                     // mediumToolStripMenuItem

                     //

                     this->mediumToolStripMenuItem->Name = L"mediumToolStripMenuItem";

                     this->mediumToolStripMenuItem->Size = System::Drawing::Size(121, 22);

                     this->mediumToolStripMenuItem->Text = L"Medium";

                     this->mediumToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::mediumToolStripMenuItem_Click);

                     //

                     // fastToolStripMenuItem

                     //

                     this->fastToolStripMenuItem->Name = L"fastToolStripMenuItem";

                     this->fastToolStripMenuItem->Size = System::Drawing::Size(121, 22);

                     this->fastToolStripMenuItem->Text = L"Fast";

                     this->fastToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::fastToolStripMenuItem_Click);

                     //

                     // maryHayToolStripMenuItem

                     //

                     this->maryHayToolStripMenuItem->Name = L"maryHayToolStripMenuItem";

                     this->maryHayToolStripMenuItem->Size = System::Drawing::Size(152, 22);

                     this->maryHayToolStripMenuItem->Text = L"E&xit";

                     this->maryHayToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::maryHayToolStripMenuItem_Click);

                     //

                     // musicToolStripMenuItem1

                     //

                     this->musicToolStripMenuItem1->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^  >(4) {this->toolStripMenuItem1,

                           this->airWolfToolStripMenuItem, this->maryHayToolStripMenuItem1, this->tresHombresToolStripMenuItem});

                     this->musicToolStripMenuItem1->Name = L"musicToolStripMenuItem1";

                     this->musicToolStripMenuItem1->Size = System::Drawing::Size(45, 20);

                     this->musicToolStripMenuItem1->Text = L"Music";

                     this->musicToolStripMenuItem1->Click += gcnew System::EventHandler(this, &Form1::musicToolStripMenuItem1_Click);

                     //

                     // airWolfToolStripMenuItem

                     //

                     this->airWolfToolStripMenuItem->Name = L"airWolfToolStripMenuItem";

                     this->airWolfToolStripMenuItem->Size = System::Drawing::Size(152, 22);

                     this->airWolfToolStripMenuItem->Text = L"Song 1";

                     this->airWolfToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::airWolfToolStripMenuItem_Click);

                     //

                     // maryHayToolStripMenuItem1

                     //

                     this->maryHayToolStripMenuItem1->Name = L"maryHayToolStripMenuItem1";

                     this->maryHayToolStripMenuItem1->Size = System::Drawing::Size(152, 22);

                     this->maryHayToolStripMenuItem1->Text = L"Song 2";

                     this->maryHayToolStripMenuItem1->Click += gcnew System::EventHandler(this, &Form1::maryHayToolStripMenuItem1_Click);

                     //

                     // tresHombresToolStripMenuItem

                     //

                     this->tresHombresToolStripMenuItem->Name = L"tresHombresToolStripMenuItem";

                     this->tresHombresToolStripMenuItem->Size = System::Drawing::Size(152, 22);

                     this->tresHombresToolStripMenuItem->Text = L"Song 3 ";

                     this->tresHombresToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::tresHombresToolStripMenuItem_Click);

                     //

                     // helpToolStripMenuItem

                     //

                     this->helpToolStripMenuItem->Name = L"helpToolStripMenuItem";

                     this->helpToolStripMenuItem->Size = System::Drawing::Size(40, 20);

                     this->helpToolStripMenuItem->Text = L"Help";

                     this->helpToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::helpToolStripMenuItem_Click);

                     //

                     // label2

                     //

                     this->label2->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;

                     this->label2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,

                           static_cast<System::Byte>(0)));

                     this->label2->Location = System::Drawing::Point(12, 317);

                     this->label2->Name = L"label2";

                     this->label2->Size = System::Drawing::Size(165, 27);

                     this->label2->TabIndex = 7;

                     this->label2->Text = L"Player 1 Score:";

                     this->label2->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;

                     //

                     // label3

                     //

                     this->label3->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;

                     this->label3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,

                           static_cast<System::Byte>(0)));

                     this->label3->Location = System::Drawing::Point(183, 317);

                     this->label3->Name = L"label3";

                     this->label3->Size = System::Drawing::Size(47, 27);

                     this->label3->TabIndex = 8;

                     this->label3->Text = L"0";

                     this->label3->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;

                     //

                     // label4

                     //

                     this->label4->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;

                     this->label4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,

                           static_cast<System::Byte>(0)));

                     this->label4->Location = System::Drawing::Point(236, 317);

                     this->label4->Name = L"label4";

                     this->label4->Size = System::Drawing::Size(165, 27);

                     this->label4->TabIndex = 9;

                     this->label4->Text = L"Player 2 Score:";

                     this->label4->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;

                     //

                     // label5

                     //

                     this->label5->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;

                     this->label5->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,

                           static_cast<System::Byte>(0)));

                     this->label5->Location = System::Drawing::Point(407, 317);

                     this->label5->Name = L"label5";

                     this->label5->Size = System::Drawing::Size(47, 27);

                     this->label5->TabIndex = 10;

                     this->label5->Text = L"0";

                     this->label5->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;

                     //

                     // toolStripMenuItem1

                     //

                     this->toolStripMenuItem1->Name = L"toolStripMenuItem1";

                     this->toolStripMenuItem1->Size = System::Drawing::Size(152, 22);

                     this->toolStripMenuItem1->Text = L"No Music";

                     this->toolStripMenuItem1->Click += gcnew System::EventHandler(this, &Form1::toolStripMenuItem1_Click);

                     //

                     // Form1

                     //

                     this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

                     this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

                     this->BackColor = System::Drawing::SystemColors::ActiveCaptionText;

                     this->ClientSize = System::Drawing::Size(468, 348);

                     this->Controls->Add(this->label5);

                     this->Controls->Add(this->label4);

                     this->Controls->Add(this->label3);

                     this->Controls->Add(this->label2);

                     this->Controls->Add(this->axWindowsMediaPlayer2);

                     this->Controls->Add(this->axWindowsMediaPlayer1);

                     this->Controls->Add(this->label1);

                     this->Controls->Add(this->pictureBox3);

                     this->Controls->Add(this->pictureBox2);

                     this->Controls->Add(this->pictureBox1);

                     this->Controls->Add(this->menuStrip1);

                     this->MainMenuStrip = this->menuStrip1;

                     this->MaximizeBox = false;

                     this->MinimizeBox = false;

                     this->Name = L"Form1";

                     this->SizeGripStyle = System::Windows::Forms::SizeGripStyle::Hide;

                     this->Text = L"Pong";

                     this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox1))->EndInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox2))->EndInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->pictureBox3))->EndInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->axWindowsMediaPlayer1))->EndInit();

                     (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->axWindowsMediaPlayer2))->EndInit();

                     this->menuStrip1->ResumeLayout(false);

                     this->menuStrip1->PerformLayout();

                     this->ResumeLayout(false);

                     this->PerformLayout();

              }

#pragma endregion

       private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

                            x=pictureBox3->Left;

                            y=pictureBox3->Top;

                            newDirection();

                            pictureBox1->Size = System::Drawing::Size(30, 48);

                      }

       private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e)

                      {

                  if(pictureBox2->Top <25)                          

                        pictureBox2->Top=25;

                     if(pictureBox2->Top >263)

                        pictureBox2->Top=263;

                     if(pictureBox1->Top <25)                       

                        pictureBox1->Top=25;

                     if(pictureBox1->Top >263)

                        pictureBox1->Top=263;

                            // if (KEY_DOWN(VK_LEFT))

                  //        label1->Text="left";                             

                  if (KEY_DOWN(VK_RIGHT))

                             {

                          //label1->Text="right";                         

                             }

                  if (KEY_DOWN(VK_UP))

                             {

                          //right paddle up

                                    if (pictureBox2->Top-10 >=23)

                                            pictureBox2->Top=pictureBox2->Top-10;

                             }

                  if (KEY_DOWN(VK_DOWN))

                  {      //right paddle down

                                      if (pictureBox2->Top+10 <=273)

                                           pictureBox2->Top=pictureBox2->Top+10;

                             }

                  if (KEY_DOWN(VK_SPACE))

                             {

                                    NewGame();

                                 timer2->Enabled=true;

                             }

                  //if (KEY_DOWN(VK_ESCAPE))

                  //        label1->Text="escape";

                  if (KEY_DOWN(65) )  //Ascii code for A (handles a too)

                              {       //left paddle up

                                    if (pictureBox1->Top-10 >=23)

                                        pictureBox1->Top=pictureBox1->Top-10;

                          //label1->Text="A";

                             }

                  if (KEY_DOWN(90))     //ascii code for Z

                             {      //left paddle down

                                     if (pictureBox1->Top+10 <=273)

                                     pictureBox1->Top=pictureBox1->Top+10;

                          //label1->Text="Z";

                             }

              }

                      void NewGame()

                      {

                            //pictureBox3->Left=230;

                            //pictureBox3->Top=150;

                            x=230;

                            y=150;

                            pictureBox3->Location::set(System::Drawing::Point(x,y));

                            newDirection();

                      }

         void newDirection()

         {

                int r;

                //r.randomize();

                r=(int)(rand()%14)+1;

                if(r==1)

                       direction=0;

                if(r==2)

                       direction=23;

                if(r==3)

                       direction=45;

                if(r==4)

                       direction=68;

                if(r==5)

                       direction=113;

                if(r==6)

                       direction=135;

                if(r==7)

                       direction=158;

                if(r==8)

                       direction=180;

                if(r==9)

                       direction=203;

                if(r==10)

                       direction=225;

                if(r==11)

                       direction=248;

                if(r==12)

                       direction=293;

                if(r==13)

                       direction=315;

                if(r==14)

                       direction=338;

         }

       private: System::Void timer2_Tick(System::Object^  sender, System::EventArgs^  e) {

                            //direction=338;

                            if(direction==338)

                            {

                                   xChange=9;

                                   yChange =4;

                            }

                             if(direction==315)

                            {

                                   xChange=7;

                                   yChange =7;

                            }

                             if(direction==293)

                            {

                                   xChange=4;

                                   yChange =9;

                            }

                             if(direction==270)

                            {

                                   xChange=0;

                                   yChange =10;

                            }

                             if(direction==248)

                            {

                                   xChange=-4;

                                   yChange =9;

                            }

                             if(direction==225)

                            {

                                   xChange=-7;

                                   yChange =7;

                            }

                             if(direction==203)

                            {

                                   xChange=-9;

                                   yChange =4;

                            }

                              if(direction==180)

                            {

                                   xChange=-10;

                                   yChange =0;

                            }

                             if(direction==158)

                            {

                                   xChange=-9;

                                   yChange =-4;

                            }

                             if(direction==135)

                            {

                                   xChange=-7;

                                   yChange =-7;

                            }

                             if(direction==113)

                            {

                                   xChange=-4;

                                   yChange =-9;

                            }

                             if(direction==90)

                            {

                                   xChange=0;

                                   yChange =-10;

                            }

                             if(direction==68)

                            {

                                   xChange=4;

                                   yChange =-9;

                            }

                             if(direction==45)

                            {

                                   xChange=7;

                                   yChange =-7;

                            }

                             if(direction==23)

                            {

                                   xChange=9;

                                   yChange =-4;

                            }

                             if(direction==0)

                            {

                                   xChange=10;

                                   yChange =0;

                            }

                             //********************

                             //bouncing off the  top

                             if(y<32)

                             {

                                    if (direction==158)

                                           direction=203;

                                    if (direction==135)

                                           direction=225;

                                    if (direction==113)

                                           direction=248;

                                    if (direction==68)

                                           direction=293;

                                    if (direction==45)

                                           direction=315;

                                    if (direction==23)

                                           direction=338;

                                    boing();

                      y=32;

                             }

                             //*********************

                             //bouncing off the bottom

                             if(y>295)

                             {

                                    if (direction==203)

                                           direction=158;

                                    if (direction==225)

                                           direction=135;

                                    if (direction==248)

                                           direction=113;

                                    if (direction==293)

                                           direction=68;

                                    if (direction==315)

                                           direction=45;

                                    if (direction==338)

                                           direction=23;

                      y=295;

                                    boing();

                             }

                             //********************

                             y=y+ballSpeed*yChange;

                             x=x+ballSpeed*xChange;

                              pictureBox3->Location::set(System::Drawing::Point(x,y));

                             //pictureBox3->Left=x;

                             //pictureBox3->Top=y;

                             //********************

                             //right paddle

                             if(pictureBox3->Left > pictureBox2->Left-14 && pictureBox3->Left < pictureBox2->Left+10)

                             {

                                    if(pictureBox3->Top > pictureBox2->Top-10 && pictureBox3->Top<pictureBox2->Top+2)

                                    {

                                           direction =113;

                                           paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox2->Top+1 && pictureBox3->Top<pictureBox2->Top+8)

                                    {

                                           direction =135;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox2->Top+9 && pictureBox3->Top<pictureBox2->Top+15)

                                    {

                                           direction =158;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox2->Top+16 && pictureBox3->Top<pictureBox2->Top+22)

                                    {

                                           direction =180;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox2->Top+23 && pictureBox3->Top<pictureBox2->Top+29)

                                    {

                                           direction =203;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox2->Top+30 && pictureBox3->Top<pictureBox2->Top+36)

                                    {

                                           direction =225;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox2->Top+37 && pictureBox3->Top<pictureBox2->Top+42)

                                    {

                                           direction =248;

                                            paddleHit();

                                    }

                             }

                             //********************

                     //left paddle

                             if(pictureBox3->Left > pictureBox1->Left-14 && pictureBox3->Left < pictureBox1->Left+10)

                             {

                                    if(pictureBox3->Top > pictureBox1->Top-10 && pictureBox3->Top<pictureBox1->Top+2)

                                    {

                                           direction =68;

                                           paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox1->Top+1 && pictureBox3->Top<pictureBox1->Top+8)

                                    {

                                           direction =45;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox1->Top+9 && pictureBox3->Top<pictureBox1->Top+15)

                                    {

                                           direction =23;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox1->Top+16 && pictureBox3->Top<pictureBox1->Top+22)

                                    {

                                           direction =0;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox1->Top+23 && pictureBox3->Top<pictureBox1->Top+29)

                                    {

                                           direction =338;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox1->Top+30 && pictureBox3->Top<pictureBox1->Top+36)

                                    {

                                           direction =315;

                                            paddleHit();

                                    }

                                    if(pictureBox3->Top>pictureBox1->Top+37 && pictureBox3->Top<pictureBox1->Top+42)

                                    {

                                           direction =293;

                                            paddleHit();

                                    }

                             }

                     //*********************

                     //handles scoring for player1

                     static int player2Score=0;

                     if(pictureBox3->Left>476)

                     {

                           timer2->Enabled=false;

                           player2Score++;

                     }

                           String ^p2score;

                           p2score=player2Score.ToString ();

                           label5->Text=p2score;

                     //*********************

                     //handles scoring for player1

                     static int player1Score=0;

                     if(pictureBox3->Left<-20)

                     {

                           timer2->Enabled=false;

                           player1Score++;

                     }

                           String ^p1score;

                           p2score=player1Score.ToString ();

                           label3->Text=p2score;

                      }

         private: System::Void pictureBox3_Click(System::Object^  sender, System::EventArgs^  e)

            {

               }

               void paddleHit()

               {

                      String ^mystring="bounc.wav";

              axWindowsMediaPlayer1->URL=mystring;

               }

               void boing()

               {

                      String ^mystring="bounc.wav";

              axWindowsMediaPlayer1->URL=mystring;    

               }

private: System::Void airWoldToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

               }

private: System::Void maryHayToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                      Form1::Close();                                     

               }

private: System::Void musicToolStripMenuItem1_Click(System::Object^  sender, System::EventArgs^  e) {

               }

private: System::Void airWolfToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                                    String ^mystring="wolf.mid";

              axWindowsMediaPlayer2->URL=mystring;

               }

private: System::Void maryHayToolStripMenuItem1_Click(System::Object^  sender, System::EventArgs^  e) {

                        String ^mystring="hay.mid";

              axWindowsMediaPlayer2->URL=mystring;

               }

private: System::Void slowToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                      ballSpeed=.6;

               }

private: System::Void fastToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                   ballSpeed=1.6;

               }

private: System::Void mediumToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                       ballSpeed=1;

               }

private: System::Void helpToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                      MessageBox::Show("Press Spacebar for a new ball,\nA and B Keys for player 1, Up and \nDown arrow keys for player 2.","Help for Pong...");

               }

private: System::Void tresHombresToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {

                      String ^mystring="rock.mid";

              axWindowsMediaPlayer2->URL=mystring;

               }

private: System::Void toolStripMenuItem1_Click(System::Object^  sender, System::EventArgs^  e) {

                      String ^mystring="";

              axWindowsMediaPlayer2->URL=mystring;

                       //axWindowsMediaPlayer2->URL=mystring;

               }

};

}

 (Back) 


©All rights reserved by James Krumm. Originally made available at www.caspercomsci.com. Materials here can be used, and redistributed, provided proper reference is made to the origin and author(s) of these materials. Please send any corrections or suggestions to jkrumm@caspercollege.edu. Last modified May 29, 2009.


To find out more about the Casper College Computer Science Program contact us at:

James Krumm
Department Head
Computer Science,
Wold Physical Sciences Building,
Casper College,
125 College Drive,
Casper, Wyoming 82601
(307) 268-2519 jkrumm@caspercollege.edu

[Return to Homepage]

|Home| |Computer Science| |Casper College| |Java Source Code| |C++ Source Code| |Visual C++.NET| |Visual Basic| |Assembly Source Code| |Linux| |Dice Program|

|Wyoming| |Casper Area| |American Album| |Personal Album| |Hawaii| |Denmark| |Greece| |Paris| |London| |Amsterdam| |Links| |Sitemap|