C Sharp Tutorial

Share Embed Donate


Short Description

c sharp is a lot like java. here is a tutorial for beginning to program in visual C sharp distributed free by microsoft....

Description

Visual C# Tutorial 1

Phidgets Inc.

Visual C# Tutorial 1 A Single RFID Reader in Visual C# Overview In this tutorial we will cover: •Initial setup •Creating the Graphical User Interface •Writing code to operate the Graphical User Interface and control a Phidget RFID reader This tutorial provides a starting point for learning how to use the Phidget RFID Reader and develop a feel for the way all Phidgets work. This tutorial is targeted towards those who are new to C# Programming and creating Graphical User Interfaces. However, this tutorial assumes the reader possesses an understanding of basic programming concepts. Knowledge of object oriented programming is also assumed. The source code for this application is provided with the tutorial. It is suggested though that you follow the steps outlined here to gain a firm grasp of how Visual C# works and the steps used to create the application. More examples are available in the Downloads section of the web site.

Initial Setup Please ensure that you have a working copy of Visual Studio (Visual Studio or Visual C# Express) installed on your system, and that it is up to date. Important: It is necessary to download and install the Phidget21 .NET API from the Phidgets web site, Phidget21.msi. Without this file, it is not possible to use Phidgets.

Creating the Graphical User Interface (GUI) The GUI is what you actually see when running your program. It allows you to interact with the code and make changes that can affect your Phidget.

Create a New Project To begin, open Visual Studio and create a new project. Select “Windows Application”, name the project ‘RFIDReader’ and click “Ok”. 

Phidgets Inc.

Visual C# Tutorial 1 GUI Layout

1

4

3

2

7

5 3

6 6

A program with a GUI is composed of one or more “forms”. The forms contain all of the elements necessary to interact with the computer in a graphical environment. The form for this program is the grey box on the screen. Most programs that you will be writing for Phidgets, at least to begin with, will only use one form. Applications that make use of more than one are often substantially more complicated to program. The screen you see now is called the “Form Designer”. It is useful to first set up your workspace. If

the “Toolbox” panel is not already visible, open the “View” menu ( 1 ) and select “Toolbox”. To ensure the Toolbox panel does not cover the form you are going to be working on, toggle the “pin” button ( 2 ). The various elements of the GUI, known as controls, can be placed in whatever order you wish and in any location you wish within the form. For this example, we will first place the “Labels”( 3 ) which will be used to display information. Under the “All Windows Forms” rollout, select Label. Click somewhere in the middle and upper region of the form. Repeat this action to create three labels. ‘label1’ will be used to display the tag code whenever an RFID tag is brought into the scanning distance of the antenna. ‘label2’ will be used to represent the connection status of the RFID reader, and ‘label3’ will be used to display the serial number of the connected Phidget. Note the names of your labels and the order they appear on the form, they should follow the order shown here. When working with the labels and controls in general, it is often useful to open the layout toolbar by selecting View ( 1 ) >> Toolbars >> Layout. The layout toolbar provides many helpful tools for aligning elements on the form. Select the three labels you created and perform a “Left Align” ( 4 ). If your labels are spread out vertically you can also try clicking “Make Vertical Spacing Equal” ( 5 ). You can move the labels as a group into whatever position you wish. Finally, select the ”CheckBox” tool ( 6 ) and as in the same manner as the labels, create a checkbox under the labels. Repeat this process to create a second checkbox under the previously created checkbox. Select the two checkboxes and click “Center Horizontally” ( 7 ) on the layout toolbar. At this stage, experimentation is encouraged to create a satisfactory look.



Visual C# Tutorial 1

Phidgets Inc.

Modify Properties In this step, we’ll modify the labels attached to the two checkboxes we created to display something a little bit more meaningful to our example. To do this we will have to modify those controls’ ‘Properties’. To do this, first click on checkBox1 to select it and look to the bottom right hand side of the screen. The properties panel should be visible with the name of the selected control at the top of the panel. Here the name is “checkBox1”. We will be changing the following properties: 1. Text - Set this to “Antenna”. This checkbox is going to be used to display the status of the RFID Reader’s antenna. Once that is completed, the same process can be repeated for checkBox2. However this time, set the Text property to “LED”. As is obvious, there are many different properties that can be set. A fairly good explanation can be found by clicking on each and looking to the very bottom of the screen or by searching the help file that comes with Visual Studio.

Writing the Code Visual C# and all visual programming languages are “event driven”, as such, any action you want the program to respond to calls a subroutine. As a general rule, every event requires it’s own block of code. There are three categories of action that this application must be designed to handle.

1. Program Activities - These are events such as opening or closing the program. 2. User Activities - Such as clicking the Antenna or LED checkboxes. 3. Phidget Events - Phidget events include attaching or detaching the Phidget and handling any errors that might occur.



Phidgets Inc.

Visual C# Tutorial 1 Form Load Event

While still in the Form Designer, double-click the form in order to generate the code block to handle a Load event for our form. This subroutine is triggered when the application is opened. After doubleclicking the form, a new window tab should be opened display the Code View for our form with a new block of code for our Form1_Load event. using using using using using

System.Drawing; System.Text; System.Windows.Forms; Phidgets; Phidgets.Events;

1

namespace RFIDReader { public partial class Form1 : Form { private RFID rfid; 2

3

public Form1() { InitializeComponent(); }

4

private void Form1_Load(object sender, EventArgs e) { label1.Text = “Tag: -”; label2.Text = “Status: Not Connected”; label3.Text = “Serial Number: -”; checkBox1.Checked checkBox1.Enabled checkBox2.Checked checkBox2.Enabled

5

.....

}

rfid = new RFID();

= = = =

false; false; false; false;

6 2

1. Here we’ll add two “using” statements. “Using” statements allow us to specify specific namespaces to look for classes from our referenced API libraries. In this case we are Specifying the “Phidgets” namespace and the “Phidgets.Events” namespace. This clarifies the scope of a class. If we did not declare these using statements, we would have to use the full namespace when declaring an object. In other words, to create an RFID object, we would have to write “Phidget.RFID”, but since we declared those using statements we can simply write “RFID”. 2. Here the “rfid” object is declared. Note that we declare the object outside of any subroutines and therefore it remains globally accessible (every subroutine can access it) within the scope of this class, or more specifically, this Form. By declaring the object this way, we are creating a reference to an RFID object which will be used to point to a reserved place in memory that will hold a RFID object. Whenever we want to use that object we will refer to it using the reference we created.

Now, observe later on in the code how we create the new RFID object in memory using “new RFID()”. This reserves the space for memory for the object and then creates the reference to our rfid object we created earlier. This can be thought of as acting as the object in memory’s name for the purpose of our application. So when using an object in code, such as rfid, you are actually not using the object but the reference to the object. For example, it is possible to have two objects (A and B) and to swap their references. In such a case, calling object A would actually access object B. 3. This line of code was automatically created when we double clicked on the form in the form designer and is used to define the subroutine. 4. As with ( 3 ), this portion of this line of code was also automatically created when we double clicked the form in the form designer. The specifics of this portion are not really important to most new users. In the simplest sense, it generates two objects, the first of which, sender, can be used to identify the object or event responsible for triggering the subroutine. The second object, EventArgs e, con

Visual C# Tutorial 1

Phidgets Inc.

tains other information that the subroutine is given. This structure containing sender and EventArgs e objects is very common in .NET programming. 5. This three line block of code is responsible for changing the labels. The text shown on the checkboxes was modified in the panel when laying out the GUI. Here however, the contents of the labels are modified directly within the code. Most properties found in the properties panel can be modified by the code in this same manner. The structure object.property or object.variable is a universal way of accessing or modifying information within objects. If the call contains brackets, it is a subroutine, such as object.subroutine(). It is also possible to have layered structures, as in object.property. property.subroutine(). In this case, the property actually refers to another object contained within the main object. 6. This block of code is responsible for changing some properties of the checkboxes. In this block we are clearing the checkboxes so that they will look unchecked. We are also changing the enabled property to false. Doing this will make them unusable. This is due to the fact that at this point there is no RFID device attached so the use shouldn’t be able to modify the Antenna and LED properties of the object.



Phidgets Inc.

Visual C# Tutorial 1 private void Form1_Load(object sender, { label1.Text = “Tag: label2.Text = “Status: label3.Text = “Serial Number:

-”; Not Connected”; -”;

false; false; false; false;



checkBox1.Checked checkBox1.Enabled checkBox2.Checked checkBox2.Enabled



rfid = new RFID();

}

rfid.Attach += new AttachEventHandler(rfid_Attach); rfid.Detach += new DetachEventHandler(rfid_Detach); rfid.Error += new ErrorEventHandler(rfid_Error);

2

= = = =

Handling the Phidget

EventArgs e)

1

3

void rfid_Attach(object sender, AttachEventArgs e) { label1.Text = “Tag: -”; label2.Text = “Status: Connected”; label3.Text = “Serial Number: “ + rfid. SerialNumber.ToString(); }

checkBox1.Checked checkBox1.Enabled checkBox2.Checked checkBox2.Enabled

= = = =

rfid.Antenna; true; rfid.LED; true;

It is now time to interface with the Phidget. As you can see in the code to the left, there are three important events common to all Phidgets that must be handled, these are, attach and detach, occurring when a Phidgets USB cord is connected or removed from the computer. Additionally, there is the error event which is called when the Phidget malfunctions. 1.

1

4

void rfid_Detach(object sender, DetachEventArgs e) { -”; label1.Text = “Tag: label2.Text = “Status: Not Connected”; label3.Text = “Serial Number: -”; }

2

checkBox1.Checked checkBox1.Enabled checkBox2.Checked checkBox2.Enabled

= = = =

false; false; false; false;

5

void rfid_Error(object sender, ErrorEventArgs e) { MessageBox.Show(e.Description); }

3.

rfid.close(); this.Close();

3

2.

The “Attach” event is a subroutine property of the RFID object. However, the difference in the case of event handlers is that we can “hook” more than one handler subroutine to the event handler property of the Phidget object. To do this we use the “+=” operator, which simply means in this case “take the current list of event handlers and add this new one”. When writing this line of code, you will be given the option to “auto complete” the line of code by simply pressing the tab key to fill in the rest automatically. If you do this, it will automatically generate the subroutine for the rfid_Attach event handler below. As with the “Attach” event handler above, repeat this process for the “Detach” event. If you auto complete the code, it will automatically generate the rfid_Detach event handler subroutine below as before.

6

As with the “Detach” event handler above, repeat this process for the “Error” event. If you auto complete the code, it will automatically generate the rfid_Error event handler subroutine below as before.



Visual C# Tutorial 1

Phidgets Inc.

4. Now we will look at doing the work that we want done whenever an Attach event is triggered. Firstly, when the rfid_Attach event handler subroutine was auto generated, it created a “throw” statement in the subroutine body. Delete that as it is not necessary as it only serves to warn you and the user that the subroutine isn’t finished being coded yet. We are going to remedy that right now. The first thing we want to do in an Attach event is change the text being displayed in the labels. So modify the text in label2 to read “Status: Connected” to show that a Phidget RFID is now connected to the computer. Next, change the text for label3 to read “Serial Number: ”. We will then add the value of the connected RFID Phidget’s serial number, stored in the Serial Number property of the rfid object, to the string displayed by the label by using the “+” also known as the append operator. The “toString()” subroutine for the Serial Number property will change the Serial Number from a number to a printable string version of the number. This isn’t always necessary, however some controls don’t like you sending non-string values to some of their properties so it is often best practice to use the toString() subroutine of number values before displaying them in a string based control. Lastly, we want to display the working status of the RFID Antenna and LED. There is a property for both Antenna and LED in the rfid object. Both of these properties are “bool” data types which mean they have two values: true or false. The checkbox control Checked property also uses this bool value so we can simply set the Checked property to equal the bool value of the Antenna and LED properties. Then finally, set the Enabled property for both checkboxes to true so we can change the values. 5. For the Detach event, we simply have to restore the values of the labels and checkboxes to what we and set them to initially in the Form1_Load subroutine to show that a Phidget RFID is not connected and make it so the user can’t modify the value of the checkboxes. So we can copy the code used earlier in the Form1_Load subroutine again here. 6. For the Error event, we want to display the error that occurred and to shut down the program. So first we will create a MessageBox object and display the error description which is a property of the ErrorEventArgs object e using the messagebox’s show() subroutine. The error description is a property of the ErrorEventArgs object. After displaying the message box with the error description, we will close the rfid object by calling its close() subroutine and we will do the same for the form by calling its close() subroutine. “this” in this case is referring to the form which is the current object of the class that we are running this code inside of.



Phidgets Inc.

Visual C# Tutorial 1 private void Form1_Load(object sender, e) { label1.Text = “Tag: label2.Text = “Status: Connected”; label3.Text = “Serial Number:





checkBox1.Checked checkBox1.Enabled checkBox2.Checked checkBox2.Enabled

= = = =

EventArgs

Handling the Tag Events

-”; Not

Now we must handle the RFID phidget specific events; the Tag events. The tag events are triggered when an RFID tag is brought into antenna scan range of the phidget and when a tag is taken out of range, Tag and TagLost respectively.

-”;

false; false; false; false;

rfid = new RFID(); rfid.Attach += new AttachEventHandler(rfid_ Attach); rfid.Detach += new DetachEventHandler(rfid_ Detach); 1 rfid.Error += new ErrorEventHandler(rfid_ Error);

rfid.Tag += new TagEventHandler(rfid_Tag); rfid.TagLost += new TagEventHandler(rfid_ TagLost);

} void rfid_Tag(object sender, TagEventArgs e) 2 { label1.Text = “Tag: “ + e.Tag; }

1. The “Tag” is an event that is specific to an RFID Phidget class. We hook this event subroutine exactly the same as the Attach, Detach, and Error event subroutines as before using the += operator. Also like before, we can use the auto complete by pressing the Tab key to automatically generate the rfid_Tag subroutine code. Note the method signature for this event, it uses a TagEventArgs object specific to the tag events.

3

2. As with the Tag event above, repeat this process for the TagLost event. As before, if you 4 auto complete using the Tab key it will auto generate the rfid_TagLost event handler subroutine below. 3. Now we will write the code to do the work we want done whenever a rfid_Tag event is triggered. Since we created a label to display the tag value, in this subroutine we will modify the text that the label will display to display the tag value. void rfid_TagLost(object sender, TagEventArgs e) { label1.Text = “Tag: -”; }

So in this subroutine, we will change label1’s Text property to be “Tag: ” and we will append the Tag value property from object e which is a TagEventArgs object. The TagEventArgs object is an object sent during an event that contains the information related to the event, specifically the Tag value of the scanned tag. So we will display this value in the label’s text. Your code should look like what is shown above in the rfid_Tag event handler subroutine 4. Now we will write the code to do the work we want done whenever a rfid_TagLost event is triggered. When a tag is lost, it means there is no tag in range to scan, so we should reset label1’s Text property to show that. To do this, we can simply copy the code we used to initialize label1 in the Form1_Load subroutine. In other words, the code should be label1.Text = “Tag: -”; as shown above.



Visual C# Tutorial 1

Phidgets Inc.

At this point the application is nearly complete. If you choose to test it at this stage, bringing an rfid tag in range of the RFID Reader will display the tag value in the first label when a Phidget RFID Reader is connected. When the checkboxes are clicked, it should turn on and off the Antenna and LED on the RFID Reader.

private void Form1_Load(object sender, { label1.Text = “Tag: label2.Text = “Status: label3.Text = “Serial Number:

checkBox1.Checked checkBox1.Enabled checkBox2.Checked checkBox2.Enabled



rfid = new RFID();

= = = =

false; false; false; false;

EventArgs e) -”; Not Connected”; -”;

Linking the Phidget to the Checkboxes Now we will link the checkboxes to the RFID phidgets. In other words, when the user clicks the checkboxes, we need to have code that will modify the Phidget.

1. Calling the .open() subroutine on our rfid object specifically tells rfid to search the rfid.Attach += new AttachEventHandler(rfid_ Attach); computer’s USB ports and try and detect rfid.Detach += new DetachEventHandler(rfid_ any Phidget RFIDs already connected. If it Detach); finds any, it then proceeds to call the Attach rfid.Error += new ErrorEventHandler(rfid_Error); subroutine that you have already written. rfid.Tag += new TagEventHandler(rfid_Tag); The .open() subroutine called here is in fact rfid.TagLost += new TagEventHandler(rfid_TagLost); an element common to any Phidget ob2 rfid.open(); ject that you create. Just as Phidgets.RFID 1 } was used to create the rfid object used here to interact with the RFID Reader, a private void checkBox1_CheckedChanged(object sender, EventArgs e) Phidgets.Servo object would interact with a { Servo motor control. Both objects would rfid.Antenna = checkBox1.Checked; 3 contain a number of common properties } and subroutines, including .open() and the private void checkBox2_CheckedChanged(object sender, basic events Attach, Detach, and Error. A EventArgs e) complete list can be found in the .NET API { rfid.LED = checkBox2.Checked; manual. }

2. In the Form Designer window in Visual Studio, double click on the antenna checkbox to generate the checkBox1_CheckedChanged event handler subroutine in the same fashion that we generated the Form1_Load subroutine earlier. This subroutine will allow us to modify the status of the Antenna property of the Phidget RFID, in essence allowing us to turn on and off the Antenna on the Phidget RFID. In order to do so we simply have to assign the current Checked property value of checkBox1 (the antenna checkbox) to the Antenna property of our rfid object as shown in the code above. Whenever the checkbox is clicked, this event will be triggered and change the value in the rfid object for us.



Phidgets Inc.

Visual C# Tutorial 1

3. As before, double click on the LED checkbox to generate the checkBox2_CheckedChanged event handler subroutine. This subroutine will allow us to modify the status of the LED property of the Phidget RFID, in essence allowing us to turn on and off the LED on the Phidget RFID. In order to do so we simply have to assign the current Checked property value of checkBox2 (the LED checkbox) to the LED property of our rfid object as shown in the code above. Whenever the checkbox is clicked, this event will be triggered and change the value in the rfid object for us.

Closing Subroutines The final step that must be accounted for is exiting the program and shutting everything down cleanly. Generating the Form1_FormClosing subroutine: First, open the Form Designer window once again and select the main Form. Look to the properties window at the bottom right of the screen, it should list the properties for Form1 right now.( 1 )

1 2

3

Select the “Events” menu by clicking the button that looks like a lightning bolt on the properties window. ( 2 ) Finally, locate the FormClosing event in the list of available events for the selected Form control.( 3 ) Double click the FormClosing event in order to auto generate the Form1_FormClosing event handler subroutine in the code view (shown in the next image).

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { rfid.Attach -= new AttachEventHandler(rfid_Attach); rfid.Detach -= new DetachEventHandler(rfid_Detach); rfid.Error -= new ErrorEventHandler(rfid_Error);

1

rfid.Tag -= new TagEventHandler(rfid_Tag); rfid.TagLost -= new TagEventHandler(rfid_TagLost);



rfid.close();

}

rfid = null;

3 4

2

Writing the closing subroutine code: The Form1_FormClosing subroutine ( 1 ) was auto generated in the last step from the Form Designer view. This event is triggered when Form1 is being closed, either from this.close() or by clicking the “X” button on the top right corner of the form like most windows applications. First thing we will do in the closing subroutine is “unhook” the event handlers that we had hooked to the rfid object in the Form1_ Load subroutine.( 2 ) What this does in effect is disconnects the event handlers that we created so that if an event is trig10

Visual C# Tutorial 1

Phidgets Inc.

gered while we are trying to close the application, it will essentially ignore is since we have no handler specified to handle the event. This can prevent a few errors that occur during the closing phase. Though not essential, it is recommended to use the .close() subroutine when a given Phidget object is no longer required.( 3 ) It does not delete the object, rather it disconnects the current Phidget from the program. If you wanted to use the Phidget after this command (which is not applicable in this case as the program is closing), you would need to once again call the .open() subroutine. Finally, we will set the rfid object to null to clear its reference to the RFID object we created.( 4 ) This will signal the system that the object is no longer in use and can be removed from memory once the application is closed.

Conclusion You have now completed creating the application. You should now be able to run it (the green arrow). Connect a Phidget RFID Reader and try bringing an RFID tag close to the RFID Reader and taking it away and noting the Tag display label. It should now display the tag value of the tag that was brought in scanning range of the Reader. You should also now be able to disable and enable the Antenna and onboard LED. Hopefully you now have a better understanding of Phidgets and how to begin programming with them. Every Phidget works in the same fundamental way so if you understand the creation of the rfid object, how it is used and how to modify its properties, you are well on your way to being able to use almost any Phidget. It is very important to note what you have learned in this tutorial is suitable for dealing with only one Phidget connected to the computer. If you have two or more of the same type, you will get unreliable results and not know which one the program will control. A simple method for dealing with this issue is discussed in a later tutorial.

11

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF