Taking Control with C#

John Kennedy
Microsoft Corporation

January 15, 2003

Summary: John Kennedy helps sharpen up your C# skills by showing you how to add menus and controls to your Pocket PC applications using Visual Studio .NET and the .NET Framework. (8 printed pages)

The move to C#, and therefore the move to the Microsoft .NET Framework, can be a little, shall we say, traumatic for confirmed C/C++ programmers. Okay, I'll rephrase that—starting to program in C# can be an event of earth shattering proportions, complete with paradigm shifts, complete program model re-engineering exercises, and all sorts of other mind-bending turns of phrase. However, as we're starting a new year, what better time is there to start a new programming language?

Now, I haven't really got the time to teach you how to program in C#. How exactly you go about that particular task I'll leave up to you. For example, I'm sure some of you like the academic approach of a good, dry textbook full of esoteric language examples. I'm not like that. I like to learn a language by writing applications and letting the Compiler Error Messages be my guide. If you like this approach too, I'd recommend you pick yourself up a copy of Microsoft Visual C# .NET by Mickey Williams, published by Microsoft Press, ISBN 0-7356-1290-0. Although not written for the Pocket PC, this large book contains an excellent crash course in C#, as well as using the main features of the .NET Framework. You'll find a lot of it is relevant to the Pocket PC, and it's a great starting point. Learning C# isn't necessarily as bad as you might think, and with the concrete examples from this book, you'll soon see how to piece together applications.

What's On the Menu?

After you reached and passed the "Hello World" stage of C# programming, it's useful to add a degree of user interaction. This allows you to quickly write code that is conditional, and therefore is capable of performing more than one task. It's also essential that you quickly get up to speed with the many User Interface controls present in the Pocket PC Framework implementation. After all, it's the User Interface of your program that your users will be seeing the most.

Menus are also very useful to programmers. When developing, I like to keep a menu that launches the code that I'm currently testing. I can use the menu as a shortcut into some deep inner-workings of my program. Once everything is running as it should, I can delete the menu (or, if I was being clever, use conditional code to only have the menu present in Debug mode).

If you have access to the .NET Compact Framework (and if you don't, you will be able to soon with the next release of Visual Studio® .NET), you can share in the fun by creating a default C# Smart Device Programmability PC application using the new project wizards. We can then add a menu—something that is extremely easy using the Visual Studio IDE. In fact, the latest Visual Studio release features an updated designer, and to create a menu you only need to drag and drop a menu object from the tool tray onto your form. After that, it's only a matter of entering the text you need to display.

Figure 1. Adding a menu is as simple as tying your shoelaces. Just drag and drop. And type. And click. Well, it's still easy.

In order to get to the stage where you can enter some real code, you only need double-click the menu item itself. Immediately you'll be brought into the Code View of your Form and presented with the function that your menu option will execute. In the example below, I've added a single line that causes the program to exit. Although not entirely in keeping with the Pocket PC model of applications than don't quit and simply lurk around until needed, I find it very useful to be able to kill an application when developing. If you aren't careful, every time you try to download new code to the device (emulated or actual), the existing code can get in the way. Thus, having a quick way to close the running program is very convenient.

   static void Main()
   {
      Application.Run(new Form1());
   }
   private voic menuItem2_Click(object sender, System.EventArgs e)
   {
      Application.Exit();
   }
}

Adding Simple Controls

When writing your own application, you'll quickly need to add some controls for the user to employ. Controls are the software implementation of physical switches and buttons. When you think about it, it's kind of amusing that we spend a lot of time making virtual representations of switches and buttons. Take radio buttons, for example. The circular little dimples that are mutually exclusive controls. These controls are modeled on 1970's car radios that had chunky mechanical switches used to select radio stations, and are completely obsolete. And yet, they live on in software metaphors.

Anyway, enough software philosophy (I guess I've been reading too much Douglas Copeland, who wrote Microserfs, and Donald A. Norman, who wrote The Design of Everyday Things, both of which you should read). To talk technical for a moment, the .NET Framework includes an abstract Control class from which you can derive all manner of UI controls. Buttons, list boxes, combo boxes, radio buttons, checkboxes and so on, and they are all derived from this class. Even the Form itself, the window that forms the basis of your application, is derived from the Control class.

Do you care? Well probably not, because once again you can do the drag-and-drop-thing from the UI designer to simply plop the controls you need onto your main Form. Of course, you still need to do a little behind the scenes plumbing, and that's what we're going to take a look at now.

Feeling in Good Form?

Few programs exist only as one window, or Form. Most programs will pop open dialog boxes, status boxes, message boxes, and other informational displays for the user to examine. Even on the space-limited Pocket PC screen it is a useful technique to add more "layers" of information to the screen.

Adding a new Form to your application is straightforward. From the Visual Studio .NET IDE, select your Project, and right-click. Then select Add, and Add Windows Form. You'll see the window below displayed, and then it's only a matter of picking an informative name.

Figure 2. Thinking of adding a new Form to your Project? It's easy. Use this form to add a new form of derived Form to your existing Windows Form.

The new Form will exist in your project as another Form. And of course, each Form can be viewed in either design or code format. By default, your new Form will never be instantiated. Only the default Form is actually called into existence when the application is started. In other words, if you add a new Form to your program, it's up to you to open it. If you don't, it'll just hang around as a resource and no one will ever get to see it.

Here's one way of opening that new Form. Drag a button to the first form, which will be called Form1 by default, and double-click on the button to create the code that is called when the user taps on it. Now add the following code to call this new form into existence:

MyNewForm mynewformForm = new MyNewForm ();
         
mynewformForm.ShowDialog();

I'm using the method ShowDialog() here, but you could also use Show() if you wanted to create a modeless window (not always the best idea in the Pocket PC way of the world). Modeless windows float around in a manner that doesn't require them to be closed before the rest of the application can continue. A tool palette is a good example. On the small screen of a Pocket PC, this tends to be more confusing than useful.

Passing Values to Controls in Other Forms

In the real world, as opposed to the world of esoteric code examples, it's extremely likely that you will want to send some information to the newly opened Form, and get some back.

Let's say you are asking the user to enter a string into a text box. You may want to preload the text box with some existing text, allow the user to edit it, and then retrieve the new text.

Let's demonstrate setting a control's value by altering a text label. The sequence of events is:

  1. Create a new instance of the Form that contains the control (but don't display it).
  2. Change the property corresponding to the text label of the control.
  3. Display the Form.

Assume we have added a text label called label1 to the new Form, and we can do all that with some code like this:

MyNewForm mynewformForm = new MyNewForm ();
mynewformForm.label1.Text = "Hello World";
mynewformForm.ShowDialog();

The only thing to remember is that the label1 property, by default, will be private so the code for your main Form won't be able to see it. I got around this by using the Properties dialog to set it to Public, and it worked perfectly.

Figure 3. Here's that new form. You can see I've added a button to close it.

Note   The size of the Form is not important as the Pocket PC will always expand it to fill the screen.

If you are creating a new Form that acts as a dialog box, you should also add some way for the user to close it, such as a new button with code like the following attached:

private void button1_Click(object sender, System.EventArgs e)
      {
         this.Close();
      }

That said, unless you have messed around, the new Form will have a close button in the top right for the user to click, and this works fine.

Like Some Tab?

Ah, that alternative to Coke and Pepsi in the funky 70's can. However, I'm not talking about soda. I'm talking about those little tabs that provide access to multiple pages all stored on one dialog. These can be very useful if your application has a lot of settings for the user to work through.

Before you go tab crazy though, I'd ask you to consider why your program has so many options in the first place. Remember that the Pocket PC is not a desktop computer. It's something that people are using on the go and do we really need to burden them with so many options and controls and switches?

If you are convinced you do need all these controls—and don't worry, I believe you—then a tab control might be appropriate. I was delighted when I discovered how simple it was to add tab controls because all the hard work is done for you. It's like getting a group of separate Forms for the price of one.

Here are the steps involved in adding a tab control to your own program. Each new tab page you add is available for you to drag new controls onto, making it easy to organize and manipulate them.

  1. Drag the tab control over to your Form. See? Told you it was easy.
  2. In the Properties window, click on TabPages to bring up the various settings of the Tab control.
  3. Use the TabPage Collection Editor to add and rename new tab pages. Each page is a like a blank form to which you add controls.
  4. Treat each tab page as a Form, and place the controls on it as you see fit. The Pocket PC will look after displaying the pages and controls all by itself. Itdoesn't get much simpler.
click for larger image

Figure 4. The TabPage Collection Editor has a long title and many settings, but is surprisingly simple to use.

Figure 5. Here's what the TabPage control looks like on the Pocket PC device. Neat, huh? Now you can add multiple pages of options for your poor user to manipulate while they sit on a bumpy bus, cursing your name.

Take Control

Well, I hope you've seen that adding some UI controls to a Pocket PC application is quite easy. I'm busy building up a database of more tricky things that Pocket PC developers are uncovering as they work with the C# implementation, and over the next few months I'll be bringing these to your attention. Feel free to write in with your own problems, and I'll ask the team of experts here at Microsoft for some answers. Together, we'll all make the move to C# as smooth as possible.

John Kennedy is a Technical Writer/Programmer in the Visual C++ group by day and leads a secret life as a Pocket PC developer by night.

Larry Roof heads up larryroof.com, a firm that specializes in consulting on mobile projects and training on eMbedded Visual Basic, Smart Device Programmability, and SQL Server CE.

Show: