C# Tutorial #2 Developing a Windows Forms component (part 1)

C# Tutorial #2 Developing a Windows Forms component (part 1)This tutorial shows how to develop a Windows Forms component that can be reused in any Windows Forms program. This isn’t the same as a control - but the only difference is that a control draws its own user interface while a component does not. This means that components are used for functions where no visible interface is required.

We want the component to do something useful, so we will write a component that notifies the host program if the status of one of the special keys - CapsLock, NumLock, and ScrollLock - on the keyboard changes. That is, if the key was off and is now on, or vice versa.
The component should have the following properties:
the key to check;
the polling interval (i.e. the interval at which the key status is checked);
and whether the component is enabled or not.
It should also have one event, which will be fired when the status of the relevant key changes, and one method, to allow the user manually to check the key status.
Steps to take
1. Create a new C# project, choosing ‘Class Library’ when the dialog box appears. I called this project MbKeyState and you might find it better to stick with this as it affects the namespace of the project, which is important for understanding the code later.
2. You now have the skeleton of the project, but there are two other things to do:
change the class name to KeyState (this isn’t strictly necessary but otherwise the class and the namespace it is in have the same name, which I find can be confusing)
the class must be derived from the Component class, so you will also need to add the System.Component namespace (add this below the line ‘using System’)
The class declaration should be changed to look like this:
public class KeyState : Component {
3. We will check the status of these keys by making a Windows API call at regular intervals. The API call is called GetKeyState and takes a parameter which is the internal value of the key (not its ASCII value - these keys don’t have one). Rather than use numbers which we might forget, we’ll set up an enumeration to make life easier. This should be a member variable of the class and we’ll make it public so that users of our component can use it too.

Website: www.microbion.co.uk | Filesize: 77kb
No of Page(s): 8
Click here to download C# Tutorial #2 Developing a Windows Forms component (part 1).

Related Tutorial

Tags: ,

Comments

Leave a Reply