Sei sulla pagina 1di 37

Outline

1. Using the MessageBox Class 2. Windows Forms Properties

Using the MessageBox Class The MessageBox class belongs to the System.Windows.Forms namespace and inherits from the Object class. In addition to the methods that it has it provides a Show() method to display different kinds of message boxes to the user. Some of the arguments of the Show() method are values of enumeration types such as MessageBoxButtons and MessageBoxIcons.

For example: Application.Run(new MyForm()); //Display a MessageBox MessageBox.Show(Application.ExecutablePath, Location of Executable, MessageBoxButtons.OK, MessageBoxIcon.Information);
2

MessageBoxButtons Enumerator Value AbortRetryIgnore OK OKCancel RetryCancel YesNo YesNoCancel

ENUMERATORS The Message Box Shows These Buttons Abort, Retry, and Ignore OK OK and Cancel Retry and Cancel Yes and No Yes, No, and Cancel

The MessageBoxIcons enumeration determines the icon on a message box. MessageBoxIcons ENUMERATORS Enumerator Value The Message Box Contains This Symbol Asterisk A lowercase letter i in a circle Error A white X in a circle with a red background Exclamation An exclamation point in a triangle with a yellow background
3

Hand Information None Question Stop Warning

A white X in a circle with a red background A lowercase letter i in a circle No symbol A question mark in a circle A white X in a circle with a red background An exclamation point in a triangle with a yellow background

SETTING AND ADDING PROPERTIES TO A WINDOWS FORM:A Windows form derives from several other classes, such as Object, Contro SOME IMPORTANT PROPERTIES OF THE Form CLASS Property Name Description BackColor Specifies the background color of the form BackgroundImage Specifies the background image displayed in the form ControlBox Indicates whether a control box needs to be displayed in the caption bar of the form DesktopLocation Specifies the location of the form on the Windows desktop
4

Enabled Indicates whether a control can respond to user interaction FormBorderStyle Specifies the border style of the form HelpButton Indicates whether a Help button is to be displayed on the caption bar of the form Icon Specifies the icon for the form MaximizeBox Indicates whether a maximize button is to be displayed on the caption bar of the form MaximumSize Specifies the maximum size to which the form can be resized MinimizeBox Indicates whether a minimize button is to be displayed in the caption bar of the form MinimumSize Specifies the minimum size to which the form can be resized Modal Indicates whether the form is to be displayed modally Name Specifies the name of the form Opacity Specifies the opacity level of the form
5

ShowInTaskbar Indicates whether the form is to be displayed in the Windows taskbar Size Specifies the size of the form StartPosition Specifies the starting position of the form at runtime TopMost Indicates whether the form should be displayed as the topmost

Setting Windows Form Properties Programmatically

MyForm frm1= new MyForm( ); frm1.BackColor = Color.AntiqueWhite; frm1.FormBorderStyle = FormBorderStyle.FixedSingle; frm1.Size = new Size(400,200); frm1.StartPosition = FormStartPosition.CenterScreen; frm1.MinimizeBox = false; }

1.6 Invoking Methods of Windows Forms private void Form1_Load(object sender, EventArgs e) { this.BackColor = Color.AntiqueWhite; this.FormBorderStyle = FormBorderStyle.Fixed3D; this.Size = new Size(400, 200); this.StartPosition = FormStartPosition.CenterScreen; this.MinimizeBox = false; // Create a new form and set its // properties to stay on t Form form2 = new Form(); form2.TopMost = true; form2.Opacity = 0.7; form2.Show();
8

. Using the Hide() method is equivalent to setting the forms Visible property to false. The form still exists in memory, and you can make it visible any time by calling the Show() method of the form or by setting the forms Visible property to true.

10

G U I D E D P R AC T I C E EXERCISE1.1 Create a form that enables users to set various options of the application. You want the form to have the following characteristics: It should have a thin title bar showing the text Options and a close button. The user should not be able to resize, minimize, or maximize this form It should always appear on top of the other forms in the application. It should be always displayed in the center of the screen. How would you create such a form?

11

Resizing forms
namespace MyNamespace { using System; using System.Drawing; using System.Windows.Forms; public class MyForm : System.Windows.Forms.Form { private Button btnLoad; private PictureBox pboxPhoto; public MyForm() { // Constructor this.Text = "Hello Form 1.4"; this.MinimumSize = new Size(200,200); // Create and configure the Button btnLoad = new Button(); btnLoad.Text = "&Load"; btnLoad.Left = 10; btnLoad.Top = 10; btnLoad.Click += new System.EventHandler(this.OnLoadClick); btnLoad.Anchor = AnchorStyles.Top | AnchorStyles.Left;

12

// Create and configure the PictureBox pboxPhoto = new PictureBox(); pboxPhoto.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; pboxPhoto.Width = this.Width / 2; pboxPhoto.Height = this.Height / 2; pboxPhoto.Left = (this.Width - pboxPhoto.Width) / 2; pboxPhoto.Top = (this.Height - pboxPhoto.Height) / 2; pboxPhoto.SizeMode = PictureBoxSizeMode.StretchImage; pboxPhoto.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; // Add our new controls to the Form this.Controls.Add(btnLoad); this.Controls.Add(pboxPhoto); }

13

protected void OnLoadClick(object sender, System.EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Open Photo"; dlg.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*" if (dlg.ShowDialog() == DialogResult.OK) { pboxPhoto.Image = new Bitmap(dlg.OpenFile()); } dlg.Dispose(); } public static void Main() { Application.Run(new MyForm()); } } }

14

The AnchorStyles enumeration specifies the settings available for the Anchor property in the Control class, The enumeration is part of the System.Windows.Forms namespace. An Anchor property is set for a control object using a bitwise or (with the vertical bar | operator) of the desired values.

15

The Anchor property preserves the distance from the control to the anchored edge or edges of its container. Here, the container for the button and picture box controls is the Form itself.

TRY IT! Change the Anchor settings in your program to experiment with this property. In particular, set this property for the btnLoad control to AnchorStyles.None. You will find that the control moves half the distance the form is resized in this case. Expand the form by 10 pixels horizontally, and the Load button will be 5 additional pixels from the left edge. While youre at it, take out the MinimumSize property and see what Happens? use the desktop properties from The previous table such as ControlBox and MaximumSize to see the effect on your program

16

The Dock property


The use of Anchor is fine when you have a set of controls and need to define their resize behavior.

The Anchor property does not quite work. While you could position the control at the edges of the form and anchor it to all sides, this is not the most elegant solution. Instead the framework provides the Dock property for this purpose. The Dock property is related to Anchor in that it also affects the resizing of controls. the Dock property establishes a fixed location for a control within its container by fixing it flush against a side of the form. Like Anchor, the Dock property takes its values from an enumeration, in this case the DockStyle enumeration. Note that one enumeration is plural (Anchor-Styles) since a control can be anchored to multiple sides, while the other enumeration is singular (DockStyle) since a control is docked to no sides, one side, or all .
17

18

Chapter 2
Getting started with Visual Studio .NET
1. Programming with Visual Studio .NET 2. Adding controls 3. Loading files 4. Resizing forms

19

The initial window of this program is shown in figure 2.1.

20

1-Toolbox Used to add new controls to a form. 2- Links These display various information and resources available. The Get Started link is shown. 3- Recent projects Quick access to recent projects. 4- Dockable windows One-click access (via the tabs) to various windows in the environment. 5- New Project button Click here to create a new project. 6- Solution Explorer Displays the files and resources in your solution. Note that this area contains other dockable windows. 7- Dynamic Help Instant help on topics related to your current activities.

21

Start Visual Studio. NET. Click the New Project button.

22

A project is a collection of files that produce a .NET application, such as a library (.dll) or executable (.exe).
A solution is a collection of projects that are grouped together for development or deployment purposes. The project has items: Referencesthe list of assemblies referenced by the project. These are provided to the compiler using the /references . AssemblyInfo.csa file containing the assembly information for the project. Form1.csa file containing the default Form class created for our application.

23

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace MyPhotos { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null;
public Form1() { // Required for Windows Form Designer support InitializeComponent();

Viewing the source code

// TODO: Add any constructor code after InitializeComponent call }

24

protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(300,300); this.Text = "Form1"; } #endregion static void Main() { Application.Run(new Form1()); } }

25

Visual Studio inserts comments for documenting your program and its methods. The Windows Forms Designer requires field in order to ensure that components are properly managed on the form at run time, and specifically for components that are not also Windows Forms controls. private System.ComponentModel.Container components; a Dispose method is provided to clean up objects that use resources such as file handles or database connections. A special InitializeComponent method is created for initializing the controls for the form. This method is processed by the Windows Forms Designer window whenever this design window is displayed.

26

Adding controls

we use Visual Studio .NET to add the Button and PictureBox controls to our form.

Similarly, add a Picture-Box object to the form.

27

Display the properties for the Button control. Rename the control from button1 to btnLoad. Modify the Text property for the button to be &Load. Display the PictureBox control properties. Set the (Name) property to pbxPhoto. Set the BorderStyle property to Fixed3D. Display the properties for our MainForm object. Set the Text property to MyPhotos Before you compile this task Take a look at the region marked Windows Form Designer generated code in the source file.

This region defines the InitializeComponent method where properties and other settings are defined. Your code should look something like this:
28

private void InitializeComponent() { this.btnLoad = new System.Windows.Forms.Button(); this.pbxPhoto = new System.Windows.Forms.PictureBox(); this.SuspendLayout(); // // btnLoad // this.btnLoad.Location = new System.Drawing.Point(16, 16); this.btnLoad.Name = "btnLoad"; this.btnLoad.TabIndex = 0; this.btnLoad.Text = "&Load";
// // pbxPhoto // this.pbxPhoto.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.pbxPhoto.Location = new System.Drawing.Point(40, 80); o this.pbxPhoto.Name = "pbxPhoto"; this.pbxPhoto.Size = new System.Drawing.Size(216, 160); this.pbxPhoto.TabIndex = 1; this.pbxPhoto.TabStop = false;

29

// // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.pbxPhoto, this.btnLoad} ); this.Name = "MainForm"; this.Text = "MyPhotos 2.2"; this.ResumeLayout(false); }

30

Loading files

we can load an image into the PictureBox control using the OpenFileDialog class.

As before, the Load button handler will allow the user to select a file and then load a Bitmap image of the file into our PictureBox control.
31

Event handlers in Visual Studio .NET IMPLEMENT A CLICK HANDLER FOR THE BTNLOAD BUTTON: 1- Display the MainForm.cs[Design] window (the Windows Forms Designer window). 2- Add a Click event handler for the Load button. 3- Add our code to handle the Click event. 4- Set the SizeMode property for the PictureBox control to StretchImage.

32

Exception handling
In our application, we expect the user to select a JPEG or other image file that can be opened as a Bitmap object. Most of the time, no error occurs. However, if a corrupted or invalid JPEG file is selected, or if the operating system is low on memory, then this creates an exceptional condition where it may not be possible to create our Bitmap.
our code might look like the following: if (dlg.ShowDialog() == DialogResult.OK) { try { imgPhoto.Image = new Bitmap(dlg.OpenFile()); } catch (Exception ex) { MessageBox.Show("Unable to load file: " + ex. Message); }

33

Resizing forms set the behavior for resizing using the Anchor property for our controls, and establish a minimum size for the form so that our PictureBox control does not disappear.

34

Assign the Anchor property In chapter 1 we set the Anchor property for our Button control to Top and Left, and for our PictureBox control to Top, Bottom, Left, and Right. In Visual Studio .NET, the default value of Top and Left is already set for our button, so we only need to modify the property for the pbxPhoto control. Display the properties for the PictureBox control. Use the Anchor property to anchor this control to all four sides of the form, select Top, Bottom,Left, and Right. then Click outside the dropdown dialog to set the selected 35 values.

the Button.Anchor property it uses the default value. this.pbxPhoto.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right);

36

Assign the MinimumSize property


Also we need to set the MinimumSize property to ensure that the window will never be so small that the PictureBox disappears.
Display the properties for the Form object. Set the value of the MinimumSize property to 200, 200 this.MinimumSize = new System.Drawing.Size(200, 200);

37

Potrebbero piacerti anche