Alyda ?

The domain name www.alyda.nl is active since December 2004.
 
Home arrow Tutorials arrow MS Visual Studio C# 2005 .NET
MS Visual Studio C# 2005 .NET
MS Visual Studio 2005 C# .NET Cook book Tutorials

MS Visual Studio C# 2005 .NET

After learning working with Visual Studio C++ 2005 .NET the appetite for more prolonged. According to the world of MicroSoft, C-Sharp is the way to go. So on this page you will find a Cook book tutorial how to make applications with C#.


Example #1, "Up Down Counter"

Program  that shows a counter value that can be changed by pressing the "Up" or "Down" button.

Start Microsoft Visual Studio2005, go to File -> New -> Project. The “New Project”  window will be shown:

Image

Expand the Visual C# Project types and select  Windows. Under Templates select "Windows Application". Name the project Up_Down_Counter, press OK and the Visual C# IDE places you in the Design view of the Up_Down_Counter project.

Image

If you don’t see the Toolbox go to View and select Toolbox.
Next drag three Buttons and a TextBox from the Toolbox to the Form1 field as shown below. Do not double click the buttons.

Image

Next rename the buttons. Right click on each button and select Properties. Change for button1 Text and Design (Name) into “Up”. Do the same for button2 but call this button, “Down” and call button3 “Exit”.

Image

After making this very simple GUI design we will enter some code. Double click somewhere on the (grey) form. Search in the code for the following lines (somewhere near the top) and enter below the class definition "int intCounter;":

namespace Up_Down_Counter
{
      public partial class Form1 : Form
      {
          int  intCounter;         // Counter value

 Next enter in the Form1_Load(object sender, EventArgs e) function the following code:

{
    intCounter = 0;      // Initialse variable intCounter to the value 0
    textBox1.Text = intCounter.ToString();  // Write value intCounter into textBox1
}

Return to the design view by clicking on the “Form1.cs [Design]” tab and double click on the Up button. Add the code:

private Void Up_Click(object  sender, EventArgs  e)
{
   intCounter++;
   textBox1.Text = intCounter.ToString();
}

The code for the Down button would be:

private Void Down_Click(object  sender, EventArgs  e)
{
   intCounter--;
   textBox1.Text = intCounter.ToString();
}

And for the Exit button:

private void Exit_Click(object  sender, EventArgs  e)
{
   Application.Exit();
}

This is all the code we need for the Up Down Counter. To compile and execute the program go to Debug -> Start Without Debugging. After compilation your first program will start.

 Download code (22Kb)

 Back


Example #2, "Mathematical plot program"

Program that plots a sine wave when the "Draw" button is pressed. For this example we make use of the GDI+ API.

Start Microsoft Visual Studio2005, go to File -> New -> Project. The “New Project”  window will be shown:

Image

Expand the Visual C# Project types and select  Windows. Under Templates select "Windows Application". Name the project Math_Plot, press OK and the Visual C# IDE places you in the Design view of the Math_Plot project.

Image

If you don’t see the Toolbox go to View and select Toolbox.

Drag three buttons and a PictureBox to the Form1 field.
Click once on each separate component, Right mouse click, choose properties and set each component properties as follows:

Form1:  Text -> Plot program
             Size -> 700; 300

Button1: Text -> Draw
              Name -> Draw

Button2: Text -> Clear
              Name-> Clear

Button3: Text -> Exit
              Name -> Exit

PictureBox1: Size -> 500; 200
                     BackColor -> select Custom -> select Black

The end result should look as shown in the following figure.

Image

When all properties are set double click on the gray colored field and each separate button. When double clicking on the tools, code will be generated on the Form1.cs page. Click on the Form1.cs[Design] tab to switch back to the GUI of your program. Next create a paint event handler by selecting the Picturebox, go to properties and click on the Events button (yellow lightning icon). Enter in the field Appearance -> Paint the name of the eventhandler. In this example we give the eventhandler the name PB_paint.

Image

Click on the Form1.cs tab and enter the following code:

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

namespace Math_Plot
{
    public partial class Form1 : Form
    {
        float point1x, point1y, point2x, point2y;
        string Graph_command = null;                // Define and init. command flag

        Pen myPen = new Pen(Color.Red, 1);          //Create a Pen instance

        public Form1()
        {
            InitializeComponent();
            Draw.Enabled = true;                    // Enabled Draw button
            Clear.Enabled = false;                  // Disable Clear button
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void PB_paint(object sender, PaintEventArgs e)
        {
            int i;
            Graphics G;

            G = e.Graphics;

            switch (Graph_command)
            {
                case "Draw_sine":
                    {
                        //Define starting point
                        point1x = 0.0F;
                        point1y = 100.0F;
                        i = 0;                      // Initialize counter i value

                        while (i < 500)             // Draw a sine wave
                        {
                            point2y = (float)(100 - (50.0 * (Math.Sin((i / 50.0) * 2 * Math.PI))));
                            point2x = i;
                            G.DrawLine(myPen, point1x, point1y, point2x, point2y);
                            point1y = point2y;
                            point1x = point2x;
                            i++;
                        }
                        break;
                    }
                case "Clear_graph":
                    {
                        G.Clear(Color.Black);        // Clear pictureBox1
                        Graph_command = null;        // Reset the command flag
                        break;
                    }
            }
        }

        private void Draw_Click(object sender, EventArgs e)
        {
            Graph_command = "Draw_sine";            // Set the command flag to "Draw_sine"
            Draw.Enabled = false;                   // Enabled Draw button
            Clear.Enabled = true;                   // Disable Clear button
            pictureBox1.Invalidate();               // Repaint the graphics
        }

        private void Clear_Click(object sender, EventArgs e)
        {
            Graph_command = "Clear_graph";          // Set the command flag to "Clear_graph"
            Draw.Enabled = true;                    // Enabled Draw button
            Clear.Enabled = false;                  // Disable Clear button
            pictureBox1.Invalidate();               // Repaint the graphics
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();                     // Stop program
        }
    }

 To compile and execute the program go to Debug -> Start Without Debugging.

 Download  code (22kb)

  Back


Example #3, "Controlling devices using NI-GPIB/RS232 Controllers"

This example demonstrates how to communicate with devices using GPIB or RS232 interfaces. The device which is used to communicate with, in this example, is an Agilent 34401A 6.5 digit multimeter. The device is arbitrary. As long as the device is equipped with a GPIB or RS232 interface this example should work. Note that commands send or received to and from the multimeter differs from any other device. Consult your device manual for the proper commands.

What do you need? First of all you need to install MAX, the NI Measurement and Automation Explorer. MAX provides access to your National Instruments products, in this case the NI GPIB controller or the "legacy" RS232 interface.
National Instruments also provides you with a free tool called VISA (Virtual Instrument Software Architecture). VISA provides the programming interface between the hardware and development environments such as LabVIEW, LabWindows/CVI, and Measurement Studio for Microsoft Visual Studio. Download and install VISA.
It might be needed to also install NI Measurement Studio to make this example work. Measurement Studio was already installed on my computer when writing this example. When I'm in the opportunity to verify if Measurement Studio is needed this text will be altered.

Start Microsoft Visual Studio2005, go to File -> New -> Project. The “New Project”  window will be shown:

Image

Expand the Visual C# Project types and select  Windows. Under Templates select "Windows Application". Name the project GPIB, press OK and the Visual C# IDE places you in the Design view of the GPIB project.

If you don’t see the Toolbox go to View and select Toolbox. Place two buttons and one TextBox on the Form1 field. Click once on each separate component, Right mouse click, choose properties and set each component properties as follows:

Button1: Text -> Send
              Name -> Send_msg

Button2: Text -> Exit
              Name -> Exit

When all properties are set, double click on the gray colored field and each separate button. When double clicking on the buttons, code will be generated on the Form1.cs page. Click on the Form1.cs[Design] tab to switch back to the GUI of your program.

Image

Click on the Form1.cs tab and enter the following code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NationalInstruments;
using NationalInstruments.UI;
using NationalInstruments.UI.WindowsForms;
using NationalInstruments.VisaNS;

namespace GPIB
{
    public partial class Form1 : Form
    {
        private MessageBasedSession mbSession;
       
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                mbSession = (MessageBasedSession)ResourceManager.
                    GetLocalManager().Open("GPIB0::9::INSTR");
            }
            catch (InvalidCastException)
            {
                MessageBox.Show("Resource selected must be a message-based session");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }

        private void Send_msg_Click(object sender, EventArgs e)
        {
            try
            {
                // Send command MEAS:VOLT:DC? and store responce into responceString.
                string responseString = mbSession.Query("MEAS:VOLT:DC?");

                // Remove lineline character (\n) from the received string.
                responseString = responseString.Replace("\n", "");

                // Replace . for , otherwise the scientific to float parsing fails
                responseString = responseString.Replace(".", ",");

                // Convert scientific notation to float.
                float Measured_val = float.Parse(responseString);

                // Write measured value into textBox1.
                textBox1.Text = Measured_val.ToString("F7");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            mbSession.Dispose();
            Application.Exit();                     // Stop program
        }
    }
}

Expand, in your Solution Explorer, References. Right click on References and select "Add Reference...". Under the .NET tab select the references: National Instruments Common, National Instruments User Interface Library and National Instruments windows Forms Controls.

The Open method of the ResourceManager objects accepts as a parameter the resource name of the instrument as a string. In this example the used multimeter GPIB address is 9. To find the resource name open the Measurement & Automation Explorer, expand "Devices and Interfaces", expand your GPIBn interface board, click on Instrumentn and select VISA Properties tab. The resource name should be given in the VISA properties windows, in this case GPIB::9::INSTR.

Image

For more information read the "NI C# and Visual Basic.Net Instrument Control Tutorial".

You can also download a similar example but then based on a RS232 interface.

Download GPIB interface code (27Kb)Download RS232 interface code (27Kb) Back


Example #4, "Data Acquisition using a NI Multifunction DAQ"

This example shows a simple program how to acquire a voltage from one of the analoge input channels and output a voltage on one of the output channels. In this example I used a NI PCI-6036E Data Acquisition board. Any other NI Data Acquisition board will do as long as the board is equipped with analog in and output channels.
Make sure, before you start writing a program, that the Data Acquisition board is recognized in the Measurement & Automation Explorer and that DAQmx is installed.

Start Microsoft Visual Studio2005, go to File -> New -> Project. The “New Project”  window will be shown. Expand the Visual C# Project types and select  Windows. Under Templates select "Windows Application". Name the project DAQ.

Image

Press OK and the Visual C# IDE places you in the Design view of the DAQ project.
Drag from the Toolbox (View and select Toolbox) the following tools onto the form: one Button, two Labels, one NumericUpDown, one TextBox and one Timer. You should see something like this:

Image

Right click on "button1" and select Properties. Change the button1 Text and Design (Name) into Exit.
Right click on "label1" and select Properties. Change the label1 Text into "Required Voltage [V]". Change the text of label2 into "Measured Voltage [V]".
Finally right click on the numericUpDown tool, select properties and change the following parameters:
  DecimalPlaces: 3
  Increment: 0.1
  Maximum: 10
  Minimum: -10

Image

Double click on the numericUpDown, Timer1 and Exit button. When double clicking on each tool, code will be automatically generated. Complete the code like presented below.

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

namespace DAQ
{
    public partial class Form1 : Form
    {
        private Task AITask;
        private Task AOTask;

        public Form1()
        {
            InitializeComponent();
            // Call function numericUpDown1_ValueChanged once. Reads
            // the numericUpDown1 value and set output DAC accordingly.
            numericUpDown1_ValueChanged(this, new EventArgs());

            // Enable timer1
            timer1.Enabled = true;
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            AOTask = new Task();

            // Create a virtual output channel
            AOTask.AOChannels.CreateVoltageChannel
                ("dev1/ao0", "", -10.00, 10.00, AOVoltageUnits.Volts);

            AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter
                (AOTask.Stream);

            writer.WriteSingleSample(true, Convert.ToDouble(numericUpDown1.Value));
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            AITask = new Task();

            // Create a virtual input channel
            // Nrse = 10078, Rse = 10083, Differential = 10106,
            // Pseudodifferential = 12529, -1 = default (set by MAX).
            AITask.AIChannels.CreateVoltageChannel("dev1/ai0", "",
                (AITerminalConfiguration)(10083), -10.00, 10.00, AIVoltageUnits.Volts);

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader
                (AITask.Stream);

            double[] acq_val = reader.ReadSingleSample();
            textBox1.Text = acq_val[0].ToString("F3");
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();                     // Stop program
        }
    }
}

Before testing the program include the DAQmx reference. Go to the Solution Explorer, right click References and select "Add Reference...". Select , under the .NET tab, "National Instruments DAQmx" and click OK.

Image

That's it! To test the program press Ctrl+F5 (Start without debugging).

Some MS Visual Studio 2005 examples based on .NET 2.0 Framework:
Without Measurement Studio (DAQmx required):
Program Files\National Instruments\MeasurementStudioVS2005\DotNET\Examples\DAQmx
With Measurement Studio (DAQmx and Measurement Studio required):
Program Files\National Instruments\MeasurementStudioVS2005\DotNET\Examples\DAQmxwithUI

When DAQmx is installed more information can be found in the "NI-DAQmx .NET Framework 2.0 Help". Go to Start -> Programs -> National Instruments -> NI-DAQ -> NI-DAQmx .NET Framework 2.0 Help. Select in the toolbar "Contents", expand "NI Measurement Studio Help" and go to "Where to find examples".

 Download  example (26Kb)

 Back


Example #5, "Web based Up Down Counter" 

Start Microsoft Visual Studio2005, go to File -> New -> Project. The “New Project”  window will be shown:

 

 Download example (Kb)

 Back


Example #6, "FileBrowser"

This example shows how to browse for a file. The result is presented in two textboxes. One textbox shows the path that contains the selected file. The second textbox shows the selected file.

Image

Place on the form two TextBoxes and place above each TextBox a Label. Name the Label above TextBox1 "Path" a the Label above TextBox2 "Filename. Also include a menuStrip. Make on the Menustrip two entries. One entry called "Browse" and the second one "Exit". Double click on the Menustrip Browse and on the Menustrip Exit. Enter the source code below.

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

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

        private void browseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Configure open file dialog box
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = "C:\\";
            dlg.FileName = "";                                  // Default file name
            dlg.DefaultExt = ".exe;.com";                // Default file extension
            dlg.Filter = "Programma|*.exe;*.com";   // Filter files by extension

            DialogResult result = dlg.ShowDialog(); // result = true is a file is
                                                    // selected.

            if (result == DialogResult.OK)
            {
                string filename = dlg.FileName;
                int Char_Pos = filename.LastIndexOf("\\"); // Position last "/" char

                string path = filename.Substring(0, Char_Pos); // Extract path
                filename = filename.Substring(Char_Pos + 1);   // Extract filename

                textBox1.Text = path;
                textBox2.Text = filename;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();                     // Exit the application
        }
    }
}

 
  Download example (24Kb)

 Back


Tips and Tricks

  •  Tools do not show up in the Toolbox after adding a Reference
    Try the following workaround go to Tools -> Choose Toolbox Items.. -> Browse -> Select the assembly from the project you want in your toolbox.

 


Links

Microsoft Visual C# 2005 Express Edition Programming for the Absolute Beginner
Aneesha Bakharia
ISBN 13: 978-1-59200-818-6 © 2006
ISBN 10: 1-59200-818-6
Publish date: December 21, 2005
360 pages
Softcover
Thomson Course Technology

Brantique

A synopsis of the various keywords in C#

Microsoft .NET Framework Version 2.0 Redistributable Package (x86):
Size 22.4Mb, date: 22/03/06
http://www.microsoft.com/downloads/details.aspx?FamilyID=0856eacb-4362-4b0d-8edd-aab15c5e04f5&displaylang=en

National Instruments Discussion Forums

C# and Visual Basic .Net Instrument Control Tutorial

National instrument Measurement Studio
National Instruments DAQmx
National Instruments VISA   Download latest free NI VISA.NET API (NI-VISA) API/Code Library.

Back

 
Next >
© 2020 www.alyda.nl
Joomla! is Free Software released under the GNU/GPL License.