0% found this document useful (0 votes)
42 views16 pages

OOP Reviewer 2

This document provides an overview of Windows forms programming in C# using the System.Drawing and System.Windows.Forms namespaces. It discusses key classes like Form, Point, Size, Rectangle, Color, and Font in System.Drawing for basic drawing functionality. It also covers controls, events, and properties in System.Windows.Forms for building graphical user interfaces with forms, buttons, textboxes and other common controls. The document demonstrates how to create a simple forms application either by hand in a text editor or using the Visual Studio designer.

Uploaded by

Adrian Cuevas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views16 pages

OOP Reviewer 2

This document provides an overview of Windows forms programming in C# using the System.Drawing and System.Windows.Forms namespaces. It discusses key classes like Form, Point, Size, Rectangle, Color, and Font in System.Drawing for basic drawing functionality. It also covers controls, events, and properties in System.Windows.Forms for building graphical user interfaces with forms, buttons, textboxes and other common controls. The document demonstrates how to create a simple forms application either by hand in a text editor or using the Visual Studio designer.

Uploaded by

Adrian Cuevas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Introduction in developing C# program using Console

Creating Hello World Program

A C# program consists of the following parts:

Namespace declaration

A class

Class methods

Class attributes

A Main method

Statements and Expressions

Comments

Hello World in C#

Hello World in C#

The first line of the program using System; - the using keyword is used to include the System namespace
in the program. A program generally has multiple using statements.

The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.

The next line has a class declaration, the class HelloWorld contains the data and method definitions that
your program uses. Classes generally contain multiple methods. Methods define the behavior of the
class. However, the HelloWorld class has only one method Main.

The next line defines the Main method, which is the entry point for all C# programs. The Main method
states what the class does when executed.

Hello World in C#

The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.

The Main method specifies its behavior with the statement Console. WriteLine("Hello World");

WriteLine is a method of the Console class defined in the System namespace. This statement causes the
message "Hello, World!" to be displayed on the screen.

The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for a key press and
it prevents the screen from running and closing quickly when the program is launched from Visual
Studio .NET.

Note:

C# is case sensitive.

All statements and expression must end with a semicolon (;).


The program execution starts at the Main method.

Unlike Java, program file name could be different from the class name.

Compiling and Executing the Program

Start Visual Studio.

On the menu bar, choose File -> New -> Project.

Choose Visual C# from templates, and then choose Windows.

Choose Console Application.

Specify a name for your project and click OK button.

This creates a new project in Solution Explorer.

Write code in the Code Editor.

Click the Run button or press F5 key to execute the project. A Command Prompt window appears that
contains the line Hello World.

Compile a C# program by using the command-line instead of the Visual Studio IDE:

Open a text editor and add the above-mentioned code.

Save the file as helloworld.cs

Open the command prompt tool and go to the directory where you saved the file.

Type csc helloworld.cs and press enter to compile your code.

If there are no errors in your code, the command prompt takes you to the next line and generates
helloworld.exe executable file.

Type helloworld to execute your program.

You can see the output Hello World printed on the screen.

C# - Basic Syntax

C# is an object-oriented programming language.

In Object-Oriented Programming (OOP) methodology, a program consists of various objects that interact
with each other by means of actions. The actions that an object may take are called methods.

Objects of the same kind are said to have the same type or, are said to be in the same class.

SAMPLE PROGRAM

C# - Basic Syntax

C# is an object-oriented programming language.


In Object-Oriented Programming (OOP) methodology, a program consists of various objects that interact
with each other by means of actions. The actions that an object may take are called methods.

Objects of the same kind are said to have the same type or, are said to be in the same class.

C# - Basic Syntax

The using Keyword

The first statement in any C# program is: using System

The using keyword is used for including the namespaces in the program can include multiple using
statements.

The class Keyword

The class keyword is used for declaring a class.

Comments in C#

Comments are used for explaining code. Compilers ignore the comment entries. The multiline
comments C# program start with /* and terminates with the characters */. Single-line comments are
indicated by the ‘//’ symbol.

C# - Basic Syntax

Member Variables

Variables are attributes or data members of a class, used for storing data. In the preceding program, the
Rectangle class has two member variables named length and width.

Member Functions

Functions are set of statements that perform a specific task. The member functions of a class are
declared within the class. Our sample class Rectangle contain three member functions: AcceptDetails,
GetArea and Display.

Instantiating a Class

In the preceding program, the class ExecuteRectangle contains the Main() method and instantiates the
Rectangle class.

C# - Basic Syntax

Identifiers

An identifier is a name used to identify a class, variable, functions, or any other user-defined item.

The basic rules for naming classes in C# are as follows:

A name must begin with a letter could be followed by a sequence of letters, digits (0-9) or underscore.
The first character in an identifier cannot be a digit.
It must not contain embedded space or symbols such as ? - + ! @ # % ^ & * () [] {} . ; : “ ‘ / and \.
However, an underscore (_) can be used.

It should not be a C# keyword.

Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as
identifiers. However, if you want to use these keywords as identifiers, you may prefix the keyword with
the @ character.

THANK YOU!

◼ Windows Programming Using C#

◼ Forms Programming I

◼ Contents

◼ System.Drawing Namespace

◼ System.Windows.Forms Namespace

 Creating forms applications by hand

 Creating forms applications using Visual Studio designer

◼ Forms Programming

◼ Forms programming allows you to create stand-alone Windows GUI applications

◼ The API has been modernized for .NET

◼ It now supports a modern delegate-based programming model

◼ Forms programming uses

 System.Drawing

◼ Basic GDI+ functionality

 System.Windows.Forms

◼ Higher-level controls

◼ System.Drawing

◼ This namespace provides many graphic data structures which are used throughout the GUI
programming model

◼ It also provides support for low-level drawing operations

◼ These can be used to draw anything, not just what is offered by the pre-built controls
◼ System.Drawing.Point

◼ Structure which represents a 2-D point

◼ Constructor

 Point(int x, int y)

◼ Properties

 X – get/set of X coordinate

 Y – get/set of Y coordinate

◼ System.Drawing.Size

◼ Structure which stores the width and height of something

◼ Constructor

 Size(int width, int height)

◼ Properties

 Width – get/set width

 Height – get/set height

◼ System.Drawing.Rectangle

◼ Structure representing a rectangle as the point of the top-left-corner, width and height

◼ Constructor

 Rectangle(Point tlc, Size sz)

 Rectangle(int tlx, int tly, int wd, int ht)

◼ Properties

 X – get/set top left X coordinate

 Y – get/set top left Y coordinate

 Height – get/set height

 Width – get/set width

 Bottom – get Y coordinate of rectangle bottom

 Top – get Y coordinate of rectangle top

 Left – get X coordinate of right of rectangle

 Right – get X coordinate of left of rectangle

 System.Drawing.Color
◼ Structure representing an alpha-RGB color

◼ Methods

 Color FromARGB(int r, int g, int b)

 Color FromARGB(int alpha, int r, int g, int b)

◼ Properties

 A – get alpha value

 R – get red value

 G – get green value

 B – get blue value

 Black, White, Red, Green, Yellow, Cyan, Coral, Blue, etc. – get values of pre-defined
colors

 System.Drawing.Font

◼ Class representing a font, size and style

◼ Constructor

 Font(string family, int points, FontStyle style)

◼ Properties

 FontFamily – get the FontFamily value

 Style – get the FontStyle Value

 Size – get the font size

 Bold – get true if bold

 Italic – get true if italic

◼ System.Drawing.FontStyle

◼ An enumeration with members

 Bold, Italic, Regular, Strikeout, Underline

◼ The values can be ORed together to indicate that more than one style should apply at once

◼ System.Windows.Forms

◼ This namespace contains all of the controls used on the average Windows interface

◼ A control is a higher-level object composed of

 A window in which the control is drawn


 Visual parts of the control which are drawn in the window

 A set of delegates which are triggered when various events occur

◼ Form Class

◼ This is the top-level window class

◼ This class contains all other controls

◼ Normally, your top-level form inherits from the Form class

◼ Although the class has numerous methods, most of the time you interact with it via properties
and delegates

◼ Form Properties

◼ Form Events

◼ Forms provide support for a large number of events

◼ You add one or more delegates to these events

◼ When the event happens, the delegates are invoked

◼ The delegates must have the signature of an event handler

void EventHandler(object sender, EventArgs e)

◼ Form Events

◼ Form Methods

◼ Creating Windows Applications

◼ We will demonstrate how to build a simple GUI interface using a text editor

◼ Most of the time, the designer in Visual Studio will be used

◼ Doing it by hand

 Shows how it works under the hood

 Let’s you make modifications by hand

 Provides an understanding so you can create your own controls

◼ Creating Windows Applications

◼ In creating a GUI application we will use

 Application – a class with static methods to control operation of an application

 Label – a widget that can display static text or an image


 Button – a push button with a textual or image displayed. Able to respond to mouse
clicks.

◼ Creating Windows Applications

◼ The first step is to create a class which

 Inherits from Form

 Declares the widgets within it

public class GreetingForm : Form {

Label greetingLabel;

Button cancelButton;

◼ Creating Windows Applications

◼ Next, create the label and set its properties

greetingLabel = new Label();

greetingLabel.Location = new Point(16, 24);

greetingLabel.Text = "Hello, World";

greetingLabel.Size = new Size(216, 24);

greetingLabel.ForeColor = Color.Black;

◼ Creating Windows Applications

◼ Create the cancel button and set its properties

cancelButton = new Button();

cancelButton.Location = new Point(150, 200);

cancelButton.Size = new Size(112, 32);

cancelButton.Text = "&Cancel";

cancelButton.Click += new EventHandler(cancelButton_Click);

◼ Creating Windows Applications

◼ Set the properties of the main form

this.AutoScaleDimensions = new SizeF(95.0f, 95.0f);

this.ClientSize = new Size(300, 300);


this.Text = "Hello, World";

◼ Creating Windows Applications

◼ Add the controls to the form

this.Controls.Add(cancelButton);

this.Controls.Add(greetingLabel);

◼ And provide the event handler

protected void cancelButton_Click(

object sender, EventArgs e) {

Application.Exit();

◼ * see HelloForm

◼ Visual Studio Designer

◼ This is a drag and drop interface for drawing a GUI

◼ The code is automatically generated

◼ You can hook event handlers onto the events and write the code for them

◼ It speeds writing code

◼ You cannot make major modifications to the code it generates

◼ CheckBoxes

◼ Labeled boxes which can be checked or unchecked

 Checked – get/set Boolean to determine if box is checked

 CheckedChanged – delegate called when the box is checked or unchecked

◼ * see ListBoxDemo

◼ GroupBox

◼ Displays a border around a group of controls

◼ Can have optional label controlled by Text property

◼ Controls can be added by

 Placing them within the group box in the designer

 Adding to the Controls list programmatically

◼ * see TextBoxDemo
◼ Panels

◼ A panel is like a group box but does not have a text label

◼ It contains a group of controls just like group box

 BorderStyle – get/set border style as

◼ BorderStyle.Fixed3D

◼ BorderStyle.FixedSingle

◼ BorderStyle.None

◼ Radio Buttons

◼ Radio buttons are similar to checkboxes, but

 Appear slightly different

 Allow buttons to be grouped so that only one can be checked at a time

◼ A group is formed when the radio buttons are in the same container – usually a group box or
panel

◼ Radio Buttons

 Checked – get/set Boolean indicating if the button is checked

 CheckedChanged – delegate invoked when the button is checked or unchecked

 * see TextBoxDemo

◼ TextBox

◼ This is a single line or multi-line text editor

 Multiline – get/set Boolean to make multiline

 AcceptsReturn – in a multiline box, if true then pressing Return will create a new line. If
false then the button referenced by the AcceptButton property of the form, will be
clicked.

 PasswordChar – if this is set to a char, then the box becomes a password box

◼ TextBox

 ReadOnly – if true, the control is grayed out and will not accept user input

 ScrollBars – determines which scrollbars will be used: ScrollBars.None, Vertical,


Horizontal, Both

 TextAlign – get/set HorizontalAlignment.Left, Center, or Right

 TextChanged – event raised when the text is changed


◼ File Dialog

◼ The file dialog allows you to navigate through directories and load or save files

◼ This is an abstract class and you use

 OpenFileDialog

 SaveFileDialog

◼ You should create the dialog once and reuse it so that it will remember the last directory the
user had navigated to

◼ File Dialog

◼ InitialDirectory – string representing the directory to start in

◼ Filter – a string indicating the different types of files to be displayed

 A set of pairs of display name and pattern separated by vertical bars

◼ Windows Bitmap|*.bmp|JPEG|*.jpg|GIF|*.gif

◼ FilterIndex – the filter to use as an origin 1 index

◼ File Dialog

◼ FileName – the name of the file selected

◼ ShowDialog – a method to show the dialog and block until cancel or OK is clicked

if (openDialog.ShowDialog() == DialogResult.OK) {

Image img = Image.FromFile(openDialog.FileName);

pictureBox1.Image = img;

◼ * see ImageViewer

◼ Image Class

◼ An abstract class that can store an image

◼ Several concrete classes are used for image types such as BMP, GIF, or JPG

 FromFile(string fname) – loads any supported image format from a file

 FromStream(stream) – loads an image from a stream

 Height – image height

 Width – image width

◼ *see ImageViewer
◼ PictureBox Class

◼ This displays an image

 Image – assigned an Image object to display

 SizeMode – determines what to do if the image does not fit into the window

◼ Normal

◼ StretchImage

◼ AutoSize

◼ CenterImage

◼ Zoom

◼ * see ImageViewer

◼ ToolTips

◼ These are the small pop-up boxes which explain the purpose of a control

◼ To use

 Create a new tooltip in the designer

 Drop the tooltip onto the form

 The tooltip will appear on a tray below the form

◼ * see ImageViewer

◼ ToolTips

◼ ToolTips

◼ After the tooltip appears in the tray, a new tooltip property appears for every component

◼ This can be assigned different text for each component

◼ That text will be displayed when the mouse hovers over that component

◼ NumericUpDown

◼ This allows the selection of an integer from a limited range

◼ Also called a spinner

 Minimum – smallest selectable value

 Maximum – largest selectable value

 Increment – size of increment per click

 Value – the selected value


 ValueChanged – event raised when the value changes

◼ * see DateSelector

◼ MonthCalendar

◼ A control which displays a calendar for the selection of a range of dates

 MinDate – the first selectable date

 MaxDate – the last selectable date

 SelectionStart – DateTime of start of selection

 SelectionEnd – DateTime of end of selection

 DateChanged – event raised when date is changed

◼ * see DateSelector

◼ DateTimePicker

◼ Similar to a month calendar but

 Calendar pulls down and selection displayed

 More configurable

 Selects a single value, not a range

◼ Properties/methods

 Format – Long, Short, Time, Custom

 Value – DateTime value selected

 ValueChanged – event which fires when date or time changes

◼ * see DateSelector

◼ System.DateTime Structure

◼ A structure representing a date and time

◼ Constructors

 DateTime(int d, int m, int y)

 DateTime(int d, int m, int y, int h, int m, int s)

◼ Properties

 Now – returns a DateTime object set to the current local time

◼ DateTime

◼ Day – day from 1-31


◼ Month – month from 1-12

◼ Year – tear from 1-9999

◼ Hour – from 0-23

◼ Minute – minute from 0 -59

◼ Second – second from 0 -59

◼ Millisecond – millisecond from 0-999

◼ DateTime

 DayOfWeek – get enumeration of Sunday, Monday,…

 DayOfYear – day of year from 1 – 366

◼ Methods

 DateTime AddYears(double value)

 DateTime AddMonths(double value)

 DateTime AddDays(double value)

 DateTime AddHours(double value)

 DateTime AddSeconds(double value)

 DateTime AddMilliseconds(double value)

◼ DateTime

 TimeSpan Subtract(DateTime)

 int CompareTo(DateTime)

 static DateTime Parse(string)

 ToLongDateString()

 ToShortDateString()

 ToLongTimeString()

 ToShortTimeString()

 ListBox

◼ The ListBox presents a list of items which can be selected

◼ A scrollbar is displayed if needed

 MultiColumn – displays list as multiple columns

 SelectedIndex – index of selected item


 SelectedIndices – collection of selected indices

 SelectedItem – the selected item

 ListBox

 SelectedItems – collection of selected items

 SelectionMode – how items can be selected

◼ None – no selection

◼ One – single selection

◼ MultiSimple – each click selects additional item

◼ MultiExtended – uses shift and control keys

 Sorted – if true the items will be sorted alphabetically

◼ ListBox

 Items – a collection of items in the list box

 ClearSelected – method to clear selection

 GetSelected – returns true if the parameter passed is selected

 SelectedIndexChanged – event when selection changes

◼ * see ListBoxDemo

◼ Populating a ListBox

◼ Any object can be placed into a ListBox

◼ The display is generated by ToString()

for(int i = 0; i < 50; i++) {

listBox1.Items.Add(

"Item " + i.ToString());

◼ ComboBox

◼ A combo box is like a list but lets you displays a selected value.

◼ The list pulls down when a selection is being made.

◼ Options allow the selected text to be editable or to require it to be selected from the drop-down
list

◼ ComboBox
◼ DropDownStyle –

 Simple – text is editable & list always visible

 DropDown – default indicating text is editable & user must click to see list

 DropDownList – value is not editable & user must click to see list

◼ Items – the collection of items in the list

◼ ComboBox

◼ MaxDropDownItems – max number of items in pulldown before scrollbar used

◼ SelectedIndex – index of selection

◼ SelectedItem – selected item

◼ Sorted – whether entries are sorted

◼ SelectedIndexChanged – event raised when selection changes

You might also like