Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Notes on computer science, Study notes of Computer Science

Notes related to computer science

Typology: Study notes

2022/2023

Uploaded on 10/02/2023

drama-kc
drama-kc 🇮🇳

4 documents

1 / 39

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Overview of the System.Windows.Forms Namespace
Like any namespace, System.Windows.Forms is composed of various classes, structures,
delegates, interfaces, and enumerations.
System.Windows.Forms namespace can be grouped into the following broad categories:
1. Core infrastructure: These are types that represent the core operations of a .NET Forms
program (Form, Application, etc.) and various types to facilitate interoperability with
legacy ActiveX controls.
2. Controls: These are types used to create rich UIs (Button, MenuStrip, ProgressBar,
DataGridView, etc.), all of which derive from the Control base class. Controls are
configurable at design time and are visible (by default) at runtime.
3. Components: These are types that do not derive from the Control base class but still
provide visual features to a .NET Forms program (ToolTip, ErrorProvider, etc.). Many
components (such as the Timer) are not visible at runtime, but can be configured visually
at design time.
4. Common dialog boxes: Windows Forms provides a number of canned dialog boxes for
common operations (OpenFileDialog, PrintDialog, etc.). As you would hope, you can
certainly build your own custom dialog boxes if the standard dialog boxes do not suit your
needs.
Core Types of the System.Windows.Forms Namespace
Working with the Windows Forms Type
Building a Main Window by Hand
To begin learning about Windows Forms programming, create a new folder on your hard drive
(e.g., C:\MyFirstWindow) and create a new file within this directory named MainWindow.cs using
your editor of choice.
In the world of Windows Forms, the Form class is used to represent any window in your
application.
This includes a topmost main window in a single-document interface (SDI) application, modeless
and modal dialog boxes, and the parent and child windows of a multiple-document interface
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27

Partial preview of the text

Download Notes on computer science and more Study notes Computer Science in PDF only on Docsity!

Overview of the System.Windows.Forms Namespace

  • Like any namespace, System.Windows.Forms is composed of various classes, structures, delegates, interfaces, and enumerations.
  • System.Windows.Forms namespace can be grouped into the following broad categories:
    1. Core infrastructure: These are types that represent the core operations of a .NET Forms program (Form, Application, etc.) and various types to facilitate interoperability with legacy ActiveX controls.
    2. Controls : These are types used to create rich UIs (Button, MenuStrip, ProgressBar, DataGridView, etc.), all of which derive from the Control base class. Controls are configurable at design time and are visible (by default) at runtime.
    3. Components : These are types that do not derive from the Control base class but still provide visual features to a .NET Forms program (ToolTip, ErrorProvider, etc.). Many components (such as the Timer) are not visible at runtime, but can be configured visually at design time.
    4. Common dialog boxes : Windows Forms provides a number of canned dialog boxes for common operations (OpenFileDialog, PrintDialog, etc.). As you would hope, you can certainly build your own custom dialog boxes if the standard dialog boxes do not suit your needs. Core Types of the System.Windows.Forms Namespace

Working with the Windows Forms Type

Building a Main Window by Hand

  • To begin learning about Windows Forms programming, create a new folder on your hard drive (e.g., C:\MyFirstWindow) and create a new file within this directory named MainWindow.cs using your editor of choice.
  • In the world of Windows Forms, the Form class is used to represent any window in your application.
  • This includes a topmost main window in a single-document interface (SDI) application, modeless and modal dialog boxes, and the parent and child windows of a multiple-document interface

(MDI) application. When you are interested in creating and displaying the main window in your program, you have two mandatory steps:

  1. Derive a new class from System.Windows.Forms.Form.
  2. Configure your application’s Main() method to invoke Application.Run(), passing an instance of your Form-derived type as an argument. using System; using System.Windows.Forms; namespace MyWindowsApp { public class MainWindow : Form { // Run this application and identify the main window. static void Main(string[] args) { Application.Run(new MainWindow()); } } }
    • In addition to the always present mscorlib.dll, a Windows Forms application needs to reference the System.dll and System.Windows.Forms.dll assemblies.
    • The default C# response file (csc.rsp) instructs csc.exe to automatically include these assemblies during the compilation process, the /target:winexe option of csc.exe instructs the compiler to generate a Windows executable.
    • To compile your C# code file, open a Visual Studio 2005 command prompt and issue the following command: csc /target:winexe *.cs Figure : A simple main window Windows Forms Honoring the Separation of Concerns
    • Currently, the MainWindow class defines the Main() method directly within its scope.
    • If you prefer, you may create a second static class, that is responsible for the task of launching the main window, leaving the Form-derived class responsible for representing the window itself: namespace MyWindowsApp {
  • Following list represent an “application-level” trait such as company name, version number, and so forth.
  1. CompanyName Retrieves the value of the assembly-level [AssemblyCompany] attribute
  2. ExecutablePath Gets the path for the executable file
  3. ProductName Retrieves the value of the assembly-level [AssemblyProduct] attribute
  4. ProductVersion Retrieves the value of the assembly-level [AssemblyVersion] attribute
  5. StartupPath Retrieves the path for the executable file that started the application Finally, the Application class defines various static events, some of which are as follows: a. ApplicationExit : Occurs when the application is just about to shut down b. Idle : Occurs when the application’s message loop has finished processing the current batch of messages and is about to enter an idle state (as there are no messages to process at the current time) c. ThreadExit : Occurs when a thread in the application is about to terminate To illustrate some of the functionality of the Application class, let’s enhance your current MainWindow to perform the following:
  • Reflect over select assembly-level attributes.
  • Handle the static ApplicationExit event. The first task is to make use of select properties in the Application class to reflect over some assembly- level attributes. using System; using System.Windows.Forms; using System.Reflection; // Some attributes regarding this assembly. [assembly:AssemblyCompany("Intertech Training")] [assembly:AssemblyProduct("A Better Window")] [assembly:AssemblyVersion("1.1.0.0")] namespace MyWindowsApp { ... }
  • Rather than manually reflecting over the [AssemblyCompany] and [AssemblyProduct] attributes using the techniques, the Application class will do so automatically using various static properties.
  • To illustrate, implement the default constructor of MainForm as so: public class MainWindow : Form { public MainWindow() { MessageBox.Show(Application.ProductName,

string.Format("This app brought to you by {0}", Application.CompanyName)); } } Output:

  • Now, let’s equip this Form to respond to the ApplicationExit event.
  • When you wish to respond to events from within a Windows Forms application, you will be happy to find that the same event syntax detailed in Chapter 8 is used to handle GUI-based events. Therefore, if you wish to intercept the static ApplicationExit event, simply register an event handler using the += operator: public class MainForm : Form { public MainForm() { ... // Intercept the ApplicationExit event. Application.ApplicationExit += new EventHandler(MainWindow_OnExit); } private void MainWindow_OnExit(object sender, EventArgs evArgs) { MessageBox.Show(string.Format("Form version {0} has terminated.", Application.ProductVersion)); } } The System.EventHandler Delegate
  • the ApplicationExit event works in conjunction with the System.EventHandler delegate.
  • This delegate must point to methods that conform to the following signature: delegate void EventHandler(object sender, EventArgs e);
  • System.EventHandler is the most primitive delegate used to handle events within Windows Forms.
  • The first parameter of the assigned method is of type System.Object, which represents the object sending the event.
  • The second EventArgs parameter (or a descendent thereof) contains any relevant information regarding the current event.

Example: public class MainWindow : Form { protected override void OnMouseDown(MouseEventArgs e) { // Add code for MouseDown event. // Call parent implementation when finished. base.OnMouseDown(e); } }

  • While this can be helpful in some circumstances, you will often handle events using the standard C# event syntax (in fact, this is the default behavior of the Visual Studio 2005 designers). When you do so, the framework will call your custom event handler once the parent’s implementation has completed: public class MainWindow : Form { public MainWindow() { MouseDown += new MouseEventHandler(MainWindow_MouseDown); } void MainWindow_MouseDown(object sender, MouseEventArgs e) { // Add code for MouseDown event. } } Beyond these OnXXX() methods, here are a few other methods to be aware of:
    • Hide(): Hides the control and sets the Visible property to false
    • Show(): Shows the control and sets the Visible property to true
    • Invalidate(): Forces the control to redraw itself by sending a Paint event To illustrate the usefulness of some members from the Control class, let’s build a new Form that iscapable of handling the following events:
    • Respond to the MouseMove and MouseDown events.
    • Capture and process keyboard input via the KeyUp event. Example: using System; using System.Windows.Forms; using System.Drawing; namespace MyWindowsApp { public class MainWindow : Form { public MainWindow() {

Text = string.Format("Current Pos: ({0}, {1})", e.X, e.Y); } }

Determining Which Mouse Button Was Clicked

  • The MouseUp (or MouseDown) event is sent whenever any mouse button is clicked.
  • If you wish to determine exactly which button was clicked (such as left, right, or middle), you need to examine the Button property of the MouseEventArgs class.
  • The value of the Button property is constrained by the related MouseButtons enumeration.
  • Example: public MainWindow() { ... // Handle the MouseUp event. MouseUp += new MouseEventHandler(MainForm_MouseUp); } public void MainForm_MouseUp (object sender, MouseEventArgs e) { // Which mouse button was clicked? if(e.Button == MouseButtons.Left) MessageBox.Show("Left click!"); if(e.Button == MouseButtons.Right) MessageBox.Show("Right click!"); if (e.Button == MouseButtons.Middle) MessageBox.Show("Middle click!"); }

Responding to Keyboard Events

  • Processing keyboard input is almost identical to responding to mouse activity. The KeyUp and KeyDown events work in conjunction with the KeyEventHandler delegate, which can point to any method taking an object as the first parameter and KeyEventArgs as the second: void MyKeyboardHandler(object sender, KeyEventArgs e); KeyEventArgs has the members of interest shown in Table 19-7.

public class MainForm : Form { public MainForm() { ... // Listen for the KeyUp Event. KeyUp += new KeyEventHandler(MainForm_KeyUp); } private void MainForm_KeyUp (object sender, KeyEventArgs e) { MessageBox.Show(e.KeyCode.ToString(), "Key Pressed!"); } }

The Functionality of the Form Class

  • Within a event handler, you are free to configure the look and feel of the Form, prepare any contained child controls (such as ListBoxes, TreeViews, and whatnot), or simply allocate resources used during the Form’s operation (database connections, proxies to remote objects, and whatnot).
  • Once the Load event has fired, the next event to fire is Activated.
  • This event fires when the Form receives focus as the active window on the desktop.
  • The logical counterpart to the Activated event is (of course) Deactivate, which fires when the Form loses focus as the active window.
  • the Activated and Deactivate events can fire numerous times over the life of a given Form type as the user navigates between active applications.
  • WhenWhen the user has chosen to close the Form in question, two close-centric events fire: Closing and Closed.
  • The Closing event is fired first and is an ideal place to prompt the end user with the much hated (but useful) “Are you sure you wish to close this application?” message.
  • This confirmational step is quite helpful to ensure the user has a chance to save any application- centric data before terminating the program.
  • The Closing event works in conjunction with the CancelEventHandler delegate defined in the System.ComponentModel namespace.
  • If you set the CancelEventArgs.Cancel property to true, you prevent the Form from being destroyed and instruct it to return to normal operation. If you set CancelEventArgs.Cancel to false, the Close event fires and the Windows Forms application terminates, which unloads the AppDomain and terminates the process. Example: Public MainForm() { // Handle various lifetime events. Closing += new CancelEventHandler(MainForm_Closing); Load += new EventHandler(MainForm_Load); Closed += new EventHandler(MainForm_Closed); Activated += new EventHandler(MainForm_Activated); Deactivate += new EventHandler(MainForm_Deactivate); }
  • In the Load, Closed, Activated, and Deactivate event handlers, you are going to update the value of a new Form-level System.String member variable (named lifeTimeInfo) with a simple message that displays the name of the event that has just been intercepted.
  • As well, notice that within the Closed event handler, you will display the value of this string within a message box: private void MainForm_Load(object sender, System.EventArgs e) { lifeTimeInfo += "Load event\n"; } private void MainForm_Activated(object sender, System.EventArgs e)

{ lifeTimeInfo += "Activate event\n"; } private void MainForm_Deactivate(object sender, System.EventArgs e) { lifeTimeInfo += "Deactivate event\n"; } private void MainForm_Closed(object sender, System.EventArgs e) { lifeTimeInfo += "Closed event\n"; MessageBox.Show(lifeTimeInfo); } Within the Closing event handler, you will prompt the user to ensure she wishes to terminatethe application using the incoming CancelEventArgs: private void MainForm_Closing(object sender, CancelEventArgs e) { DialogResult dr = MessageBox.Show("Do you REALLY want to close this app?", "Closing event!", MessageBoxButtons.YesNo); if (dr == DialogResult.No) e.Cancel = true; else e.Cancel = false; }

Building Windows Applications with Visual Studio 2005

  • Visual Studio 2005 has a specific project type dedicated to the creation of Windows Forms applications.
  • When you select the Windows Application project type, you not only receive an application object with a proper Main() method, but also are provided with an initial Form-derived type.
  • Better yet, the IDE provides a number of graphical designers that make the process of building a UI child’s play.
  • the Toolbox groups UI controls by various categories. While most are selfexplanatory (e.g., Printing contains printing controls, Menus & Toolbars contains recommended menu/toolbar controls, etc.), a few categories deserve special mention:
  1. Common Controls: Members in this category are considered the “recommended set” of common UI controls.
  2. All Windows Forms: Here you will find the full set of Windows Forms controls, including various .NET 1.x controls that are considered depreciated.

Enabling the Deprecated Controls

  • The deprecated UI elements are still completely usable under .NET 2.0.
  • If you still wish to program with them, you can add them back to the Toolbox by right-clicking anywhere in the Toolbox and selecting Choose Items.
  • From the resulting dialog box, check off the items of interest (see Figure 19-9).

Dissecting a Visual Studio 2005 Windows Forms Project

  • Each Form in a Visual Studio 2005 Windows Application project is composed of two related C# files, which can be verified using Solution Explorer (see Figure 19 - 10).
  • Right-click the Form1.cs icon and select View Code. Here you will see a partial class that contains all of the Form’s event handlers, constructors, overrides, and any member you author yourself: namespace MyVisualStudioWinApp { public partial class MainWindow : Form { public MainWindow() { InitializeComponent(); } } }
  • The default constructor of your Form makes a call to a method named InitializeComponent(), which is defined within the related *.Designer.cs file.
  • This method is maintained on your behalf by Visual Studio 2005, and it contains all of the code representing your design-time modifications.
  • To illustrate, switch back to the Forms designer and locate the Text property in the Properties window. Change this value to something like My Test Window. Now open your Form1.Designer.cs file and notice that InitializeComponent() has been updated accordingly: private void InitializeComponent() { ... this.Text = "My Test Window"; }

Handling Events at Design Time

  • Many Windows Forms controls support such context-sensitive inline editors.
  • As far as MenuStrip is concerned, the editor allows you to quickly do the following:
    1. Insert a “standard” menu system (File, Save, Tools, Help, etc.) using the Insert Standard Items link.
    2. ChangeChange the docking and gripping behaviors of the MenuStrip.
    3. EditEdit each item in the MenuStrip (this is simply a shortcut to selecting a specific item in the Properties window).
  • For this example, you’ll ignore the options of the inline editor and stay focused on the design of the menu system.
  • To begin, select the MenuStrip control on the designer and define a standard File ➤ Exit menu by typing in the names within the Type Here prompts (see Figure 19-12).
  • Each menu item you type into the designer is represented by the ToolStripMenuItem class type.
  • If you open your *.Designer.cs file, you will find two new member variables for each item: partial class MainWindow {

private System.Windows.Forms.MenuStrip mainMenuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; }

  • When you use the menu editor, the InitializeComponent() method is updated accordingly.
  • InIn a similar fashion, the fileToolStripMenuItem variable has been updated to insert the exitToolStripMenuItem variable into its ToolStripItemCollection collection via the DropDownItems property: private void InitializeComponent() { ... // menuStrip this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem}); ... // fileToolStripMenuItem this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exitToolStripMenuItem}); ... // MainWindow this.Controls.Add(this.menuStrip1); }
  • The MenuStrip control is inserted to the Form’s controls collection.
  • To finish the initial code of this example, return to the designer and handle the Click event for the Exit menu item using the events button of the Properties window.
  • Within the generated event handler, make a call to Application.Exit: private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); }

Adding a TextBox to the MenuStrip

  • Textbox can be added to the menustrip as shown in the figure: