Visual Studio.NET and Forms

for RuBoard

Although it is perfectly feasible to create Windows Forms applications using only the command-line tools of the .NET Framework SDK, in practice it much easier to use Visual Studio.NET. You can get started by creating a Windows Application project, which provides starter code and sets up references to the required .NET libraries. You can then use the Forms Designer to drag and drop controls from a toolbox onto your forms. The Forms Designer inserts all the needed boilerplate code to make your controls work within your forms. There is a Properties window which makes it easy to set properties of your controls at design time. You can, of course, also set properties at runtime, which is what we did with our txtGreeting text box in the code shown previously.

The same Forms Designer can be used in all .NET languages. A similar Designer is available for visually drawing Web Forms, which we will discuss in Chapter 10 on ASP.NET.

Windows Forms Demonstration

The best way to become acquainted with using Visual Studio.NET to create Windows applications is to build a small application from scratch yourself. Our demonstration creates a Windows application to make deposits and withdrawals from a bank account. Do all your work in the Demos directory for this chapter.

  1. Create a new C# project BankGui of type Windows Application in the Demos folder. See Figure 6-11.

    Figure 6-11. Creating a new Windows Application project.

    graphics/06fig11.gif

  2. Open up the Toolbox by dragging the mouse over the vertical Toolbox tab on the left side of the main Visual Studio window. If the Toolbox tab does not show, you can open it from the menu View Toolbox. You can make the Toolbox stay open by clicking on the "push-pin" next to the X on the title bar of the Toolbox. (The little yellow box will say "Auto Hide" when you pause the mouse over the push-pin.)

  3. From the Toolbox, drag two labels, two textboxes, and two buttons to the form. See Figure 6-12.

    Figure 6-12. Dragging controls from the Toolbox onto a form.

    graphics/06fig12.gif

  4. Click on label1 in the Forms Designer. This will select that control in the Properties window, just beneath the Solution Explorer. You can use the Properties window to make changes to properties of controls. Change the Text property to Amount . After you type the desired value, hit the carriage return. You will then see the new text shown on the form. Figure 6-13 shows the Properties window after you have changed the Text property of the first label.

    Figure 6-13. Changing property values in the Properties window.

    graphics/06fig13.gif

  5. Similarly, change the text of label2 to Balance .

  6. Enter property values for the textboxes and buttons, as shown in Table 6-1.

Table 6-1. Property Values for Textboxes and Buttons

Name

Text

txtAmount

(blank)

txtBalance

(blank)

cmdDeposit

Deposit

cmdWithdraw

Withdraw

  1. Resize the form by dragging the sizing handles on the middle of each side. Reposition the controls as desired by dragging with the mouse, and resize the controls with the mouse, if you wish. When you are satisfied with the appearance of your form, save the project. Your form should now look similar to Figure 6-14.

    Figure 6-14. Form for BankGui application.

    graphics/06fig14.gif

  2. Add event handlers for the buttons by double-clicking on each button.

  3. Add the following code:

     public class Form1 : System.Windows.Forms.Form  {  ...     public Form1()     {        //        // Required for Windows Form Designer support        //        InitializeComponent();        //        // TODO: Add any constructor code after        // InitializeComponent call        //  txtAmount.Text = "25";   txtBalance.Text = "100";  }    ...     /// <summary>     /// The main entry point for the application.     /// </summary>     [STAThread]     static void Main()     {        Application.Run(new Form1());     }     private void cmdDeposit_Click(object sender,                                   System.EventArgs e)     {  int amount = Convert.ToInt32(txtAmount.Text);   int balance = Convert.ToInt32(txtBalance.Text);   balance += amount;   txtBalance.Text = Convert.ToString(balance);  }     private void cmdWithdraw_Click(object sender,                                    System.EventArgs e)     {  int amount = Convert.ToInt32(txtAmount.Text);   int balance = Convert.ToInt32(txtBalance.Text);   balance -= amount;   txtBalance.Text = Convert.ToString(balance);  } 
  4. Build and run the application. It should behave like a standard Windows application. You should be able to make deposits and withdrawals. Figure 6-15 illustrates the running application.

    Figure 6-15. The BankGui Windows application.

    graphics/06fig15.gif

Design Window and Code Window

The most important thing to understand about navigating Windows Forms projects in Visual Studio is switching between the Design window, where you work with controls on a form, and the Code window, where you work with source code. We can illustrate these two windows from the Demos\VsForm project, where we have provided starter code corresponding to VsForm\Step1 in the main directory for this chapter. The starter project simply displays a fixed greeting string. The state of the project at various points in the demonstration is captured in other numbered steps.

If you double-click on VsForm.sln ( Demos directory) in the Solution Explorer, you will bring up the Design window, as shown in Figure 6-16.

Figure 6-16. The Design window in a Windows Forms project.

graphics/06fig16.gif

To bring up the Code window, click on the "View Code" graphics/icon17.gif toolbar button in the Solution Explorer. This will open up the source code, and you will see horizontal tabs at the top of the principal window area, allowing you to select among the open windows. Now the Design window and the Code window for this one form are open. You may also go back to the Design window by clicking on the "View Designer" graphics/icon18.gif toolbar button. Figure 6-17 shows the open Code window.

Figure 6-17. The Code window in a Windows Forms project.

graphics/06fig17.gif

Adding an Event

  1. Build and run the starter program. This is a completely static applicationit merely displays a greeting at a fixed location.

  2. Open up the Design window of the form and click on the Events button graphics/icon02.gif of the Properties window.

  3. Find the MouseDown event. See Figure 6-18.

    Figure 6-18. Adding an event by using the Events button.

    graphics/06fig18.gif

  4. Double-click. This will automatically generate code to register a delegate for the event and provide a skeleton for a method tied to the delegate. [3]

    [3] If you cannot see this Windows Form Designer generated code, click on the little "+" on the extreme left of the editor window to open up the hidden "region."

 private void InitializeComponent()  {  ...  this.MouseDown +=   new System.WinForms.MouseEventHandler   (this.Form1_MouseDown);  }  protected void Form1_MouseDown (object sender,   System.WinForms.MouseEventArgs e)   {   }  ... 

Code for Event Handler

  1. Add the highlighted code to the mouse down event handler to set the coordinates of the greeting message. Don't forget to call Invalidate !

     protected void Form1_MouseDown (object sender,  System.WinForms.MouseEventArgs e)  {  x = e.X;   y = e.Y;   Invalidate();  } 
  2. Build and run. You should now be able to relocate the greeting by clicking the mouse button (either button will work). The project now corresponds to VsForm\Step2 .

Using the Menu Control

  1. Open up the Toolbox if not already open (click on the Toolbox vertical tab) and drag the MainMenu control graphics/icon15.gif onto the form.

  2. Type "File" and "Exit," creating a popup menu File with a menu item Exit. See Figure 6-19.

    Figure 6-19. Use the Menu Control to add a menu to a form.

    graphics/06fig19.gif

  3. In the Properties window change the names of your two menu items to "menuFile" and "menuExit."

  4. Double-click on "Exit" to add code for a File Exit event handler.

  5. Add code to the handler to exit the application.

     protected void menuExit_Click (object sender,   System.EventArgs e)  {  Application.Exit();  } 
  6. Build and run. Your menu should be operational. The project now corresponds to VsForm\Step3 .

Closing a Form

As an interesting modification to our program, let us arrange it so that whenever the user attempts to close the application, the user will be queried on whether to really close. There are several ways a window can be closed:

  • From the "X" at top right of the window

  • From the system menu at the top left of the window

  • By the keyboard Alt + F4

  • In our application, by File Exit

When a form is about to close, the Closing event is raised. You may stop the closing by setting the Cancel property in the handler for this event. (First add a handler for the event Closing in the usual way.) Just type in the MessageBox code as shown.

  protected void Form1_Closing (object sender,   System.ComponentModel.CancelEventArgs e)  {        DialogResult status = MessageBox.Show(        "Do you want to close",          "Simple Form (VS)", MessageBoxButtons.YesNo);        if (status == DialogResult.No)        {  e.Cancel = true;  }  } 

To tap into this behavior, in your handler for File Exit you should not exit the application but instead close the main window by calling the Close method:

 protected void menuExit_Click (object sender,         System.EventArgs e)  {          //Application.Exit();  Close();  } 

The project now corresponds to VSForm\Step4 . Run your program and try closing in various ways. You should always see the dialog box shown in Figure 6-20.

Figure 6-20. Dialog box that queries the user whether or not to close.

graphics/06fig20.gif

for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net