Programming Languages- C# · 2021. 1. 5. · 4 19 EEES-403 - C# Cukurova University Windows Form...
Transcript of Programming Languages- C# · 2021. 1. 5. · 4 19 EEES-403 - C# Cukurova University Windows Form...
-
1
Department of Electrical-Electronics Eng.
Cukurova University
Cukurova University
EEES 403 – C#
Programming Languages- C#
EEES-403
1
Department of Electrical-Electronics Eng.
Cukurova University
Cukurova University
EEES 403 – C#
Windows Programming
3
EEES-403 - C#
Cukurova University
Contents
• System.Drawing Namespace
• System.Windows.Forms Namespace
– Creating forms applications by hand
– Creating forms applications using
Visual Studio designer
4
EEES-403 - C#
Cukurova University
Graphical User Interfaces-GUI
• Windows applications also look different from console applications
• User Interface:
– Front end of a program
– Visual image you see when you run a program
– Algorithmic functionality stays behind GUI
– Often users of programs actually identify the interface of the program itself, when in reality, the interface is just one facet of the program.
– Algorithmic complexity is hidden behind GUI.
5
EEES-403 - C#
Cukurova University
GUI Programming
• Windows Desktop Apps– Based on .NET framework
– Windows Forms programming with C#
• Three key pieces:– Forms
– Controls
– Events
6
EEES-403 - C#
Cukurova University
Graphical User Interfaces
• Controls are placed in a container, called form,
which is an object as well. It is instance of a class
derived from predefined class Form
• Controls are objects that can display and respond
to user interaction.
http://www.google.com.tr/url?sa=i&rct=j&q=&esrc=s&frm=1&source=images&cd=&cad=rja&uact=8&ved=0CAcQjRw&url=http://www.gewamed.net/index.php?mod=partners&idp=20&ei=YpJQVfe-Nca57gbFjoPIAQ&bvm=bv.92885102,d.bGQ&psig=AFQjCNFjZKlptdHCd6K7Wo0fG63GN789-w&ust=1431430099169339http://www.google.com.tr/url?sa=i&rct=j&q=&esrc=s&frm=1&source=images&cd=&cad=rja&uact=8&ved=0CAcQjRw&url=http://www.gewamed.net/index.php?mod=partners&idp=20&ei=YpJQVfe-Nca57gbFjoPIAQ&bvm=bv.92885102,d.bGQ&psig=AFQjCNFjZKlptdHCd6K7Wo0fG63GN789-w&ust=1431430099169339
-
2
7
EEES-403 - C#
Cukurova University
Windows Applications
• Reference and import System.Windows.Forms namespace
• Class heading definition
– Includes not only the class name, but a colon followed by another class name
• Derived class (first class)
• Colon ( : ) – delimiter, separator
• Base class (second class)
•public class Form1 : Form
• Derived classes inherit from base class
8
EEES-403 - C#
Cukurova University
Windows Applications (continued)
• Text
– A property for setting/getting title bar caption
– Can be used in constructor
• Windows forms/controls offer many properties including Text, Color, Font, and
Location
• Execution begins in Main( ) method
– Main( ) is located in Program.cs file for the application
– Call to Run( ) method places application in process loop
9
EEES-403 - C#
Cukurova University
Windows Application (continued)
Windows-based form
Output
generated
from
Windows0
application
10
EEES-403 - C#
Cukurova University
Using C# & Visual Studio to Create
Windows based Applications
• Primitive approach
– Manually create Win based application in C# using a
text editor like Notepad, or Textpad etc
• Professional approach
– MS Visual Studio
– Select File Menu: New >> Project
– Select Visual C#, Windows and Windows Forms
Application from Visual Studio Installed Templates
pan
11
EEES-403 - C#
Cukurova University
Visual Studio to Create Windows-Based
Applications
Windows
Forms
Application
template Browse
to
location
to store
your
work
Select
File
New
Project
Name
Visual Studio New Windows application
12
EEES-403 - C#
Cukurova University
Windows-Based Applications
Properties
Window
Design ViewToolbox Initial design screen
-
3
13
EEES-403 - C#
Cukurova University
Windows-Based Applications (continued)
Dockable windows14
EEES-403 - C#
Cukurova University
The Form as a Platform
• A Windows application form can act as a container for
additional objects.
• Objects that can be contained by forms (and are coded
by existing classes in the Foundation Class Library) are
called controls.
15
EEES-403 - C#
Cukurova University
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
16
EEES-403 - C#
Cukurova University
Windows Forms
• Task: The application
• Find appropriate property and type a new value
– Change the following Form properties:
• Text
• BackColor
• Size
• FormBorderStyle
17
EEES-403 - C#
Cukurova University
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
18
EEES-403 - C#
Cukurova University
Form Methods
Method Description
Activate Activates the window and gives it focus
Close Closes the form
Show Makes the form visible
BringToFront Moves to top of stacking order
Hide Makes the form invisible
Focus Gives the form focus
-
4
19
EEES-403 - C#
Cukurova University
Windows Form Properties
Properties Property value
Properties window
20
EEES-403 - C#
Cukurova University
Windows Form Properties (continued)
21
EEES-403 - C#
Cukurova University
Form Properties
Property Description
Location Point of to left corner
Size Size of form in pixels
Text Text displayed or caption
AutoScaleDimensions DPI resolution of display it was built for. Will be scaled to
look correct on other displays.
BackColor Background color
ForeColor Foreground or drawing color
ClientSize Size of drawing area without borders or scrollbars
Controls A collection of controls owned by the form
WindowState Whether maximized, minimized or normal
DefaultSize Size when initially created
MinimumSize Minimum size window can be resized to
MaximumSize Maximum size window can be resized to
22
EEES-403 - C#
Cukurova University 23
EEES-403 - C#
Cukurova University
Windows Form Events
• Add code to respond to events, like button clicks
• From the Properties window, select the lightning bolt (Events)
– Double-click on the event name to generate code
• Registers the event as being of interest
• Adds a heading for event-handler method
24
EEES-403 - C#
Cukurova University
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)
-
5
25
EEES-403 - C#
Cukurova University
1 - Change in
switch position
invokes switch’s
OnFlip method
2 - OnFlip Method
invokes delegate
3 - Delegate invokes light’s
OnFlipCallback method
4 - OnFlipCallback method
changes light’s state
OnFlip method
Switch Object
OnFlipCallbackmethod
Light Object
Delegate object
OnFlip method
Switch Object
26
EEES-403 - C#
Cukurova University
Delegate - I
• A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. C# delegates are similar to pointers to functions, in C or C++.
• Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
27
EEES-403 - C#
Cukurova University
Declaring a Delegate
• Delegate declaration determines the methods that can be referenced by the delegate.
• A delegate can refer to a method, which has the same signature as that of the delegate.
// declares a delegate for a method that takes a single
// argument of type string and has a void return type
delegate void MyDelegate1(string s);
28
EEES-403 - C#
Cukurova University
Instantiating a Delegate
• A Delegate Object Is Created with the new Operator
• Delegate Objects Are Immutable
// instantiating a delegate to a static method Hello
// in the class MyClass
MyDelegate1 a = new MyDelegate1(MyClass.Hello);
// instantiating a delegate to an instance method
// AMethod in object p
MyClass p = new MyClass();
MyDelegate1 b = new MyDelegate1(p.AMethod);
29
EEES-403 - C#
Cukurova University
Calling a Delegate
• Use a Statement Containing: – The name of the delegate object
– Followed by the parenthesized arguments to be passed to the delegate
// given the previous delegate declaration and
// instantiation, the following invokes MyClass'// static method Hello with the parameter "World"
a("World");
30
EEES-403 - C#
Cukurova University
Form Events
Event Description
Load Just before form is loaded the first time
Closing Just before the form is closed
Closed When the form is actually closed
Shown Occurs when a form is first displayed
ResizeBegin Resize operation has begun
ResizeEnd Resize operation has ended
-
6
31
EEES-403 - C#
Cukurova University
Windows Form Properties (continued)
Events
button
selected
Form1 events
32
EEES-403 - C#
Cukurova University
Windows Form Events (continued)
Solution Explorer window
Expand Form1.cs
node to reveal the
Form1.Designer.cs
file
33
EEES-403 - C#
Cukurova University
Simple Windows Application
• IDE separates the source code into three separate files
– Form1.cs: normally this is the only one you edit
– Form1.Designer.cs: holds the auto generated code
– Program.cs: contains the Main( ) method, where execution always begins
• Form1.cs and Form1.Designer.cs both include partial class definitions for the
Form1 class
Department of Electrical-Electronics Eng.
Cukurova University
Cukurova University
EEES 403 – C#
Your First C# Windows Form Programı
35
EEES-403 - C#
Cukurova University
//
// Printing multiple lines in a dialog Box.
using System;
using System.Windows.Forms;
..
class Welcome4
{
privete void Form1_Load(Object Sender, EventArgs e )
{
MessageBox.Show(“Welcome\nto\nC#\nprogramming!" );
}
}
The System.Windows.Forms
namespace allows the programmer to
use the MessageBox class.
This will display the contents in a message
box as opposed to in the console window.
36
EEES-403 - C#
Cukurova University
using System.Windows.Forms;
namespace MouseEvents
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
switch (e.Button)
{
case MouseButtons.Left:
MessageBox.Show("Left Button Click");
break;
case MouseButtons.Right:
MessageBox.Show("Right Button Click");
break;
default:
break;
}
}
}
}
Handling MouseEvents
http://www.google.com.tr/url?sa=i&rct=j&q=&esrc=s&frm=1&source=images&cd=&cad=rja&uact=8&ved=0CAcQjRw&url=http://www.gewamed.net/index.php?mod=partners&idp=20&ei=YpJQVfe-Nca57gbFjoPIAQ&bvm=bv.92885102,d.bGQ&psig=AFQjCNFjZKlptdHCd6K7Wo0fG63GN789-w&ust=1431430099169339
-
7
37
EEES-403 - C#
Cukurova University
Program Example
38
EEES-403 - C#
Cukurova University
Controls
• Controls are all classes
– Button, TextBox,Label, ComboBox, MainMenu,
ListBox, CheckBox, PictureBox, MenuStrip,
RadioButton, and MonthCalendar
• Each comes with its own predefined properties and methods
• Each fires events
• Each is derived from the System.Windows.Forms.Control class
39
EEES-403 - C#
Cukurova University
Controls (continued)
Dots
indicate
other
classes are
derived
from the
class
Control class hierarchy
40
EEES-403 - C#
Cukurova University
Standard Controls
Windows Forms controls41
EEES-403 - C#
Cukurova University
Controls (continued)
• Two procedures to place controls from Toolbox, double-click on control or drag and drop
– Move, resize, and delete controls
– Format controls
• Align controls
• Make same size
• Horizontal and vertical spacing
42
EEES-403 - C#
Cukurova University
Properties of the Control Class
-
8
43
EEES-403 - C#
Cukurova University
Label Objects
• Provide descriptive text or labels for other controls
• Instantiate object
Label labelName = new Label( );
• Add control to Form
this.Controls.Add(labelName);
• Set property values (some from Control class)
– Text; TextAlign; Font; Location
44
EEES-403 - C#
Cukurova University
Creating a TaxApp Form
Formatting Label objects
Add Label
objects to
Form
object…
Use
options on
FORMAT
menu
45
EEES-403 - C#
Cukurova University
Example-Creating a TaxApp
Properties set for the Form
container
46
EEES-403 - C#
Cukurova University
Adding Labels to TaxApp Form
Add Label objects, then set
their properties using the
Properties window
(View Properties window)
47
EEES-403 - C#
Cukurova University
TextBox Objects
• Used to enter data or display text during run time
– Used for both input and output • Instantiate object
TextBox textBoxName = new TextBox( );
• Add control to Form
this.Controls.Add(TextBoxName);• Interesting properties
– MultiLine, ScrollBars, MaxLength, PasswordChar, CharacterCasing
48
EEES-403 - C#
Cukurova University
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
– 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
-
9
49
EEES-403 - C#
Cukurova University
TextBox Objects (continued)
50
EEES-403 - C#
Cukurova University
Adding TextBox Objects to TaxApp Form
Add TextBox objects,
then set their property
values
51
EEES-403 - C#
Cukurova University
Button
• Enables user to click button to perform task
– If button has event-handler method and is registered as an
event to which your program is planning to respond, event-
handler method is called automatically when button
clicked
• Button object’s properties, methods, and events
– Inherits from Control
• Text, Enabled, Focused, TabIndex
52
EEES-403 - C#
Cukurova University
Adding Button Objects to TaxApp Form
Add Button objects,
then set their property
values
53
EEES-403 - C#
Cukurova University
Adding Button Objects
to TaxApp Form (continued)
Events
54
EEES-403 - C#
Cukurova University
Adding Button Objects to TaxApp Form (continued)
•When you double-click on event, an event-handler
method is created:private void btnCompute_Click(object sender, System.EventArgs e)
{
}
•AND registers click event:this.btnCompute.Click +=
new System.EventHandler
(this.btnCompute_Click);
-
10
55
EEES-403 - C#
Cukurova University
Adding Button Objects to TaxApp Form (continued)
private void btnCompute_Click(object sender, System.EventArgs e)
{ string inValue;
double purchaseAmt, percent, ans;
inValue = txtPurchase.Text;
purchaseAmt = Int32.Parse(inValue);
inValue = label5.Text; //inValue previously declared as string
inValue = inValue.Remove(inValue.Length-1, 1);
percent = double.Parse(inValue) / 100;
percent =
(double.Parse(label5.Text.Remove(label5.Text.Length-1,1))) / 100;
ans = (purchaseAmt * percent) + purchaseAmt;
txtTotalDue.Text = String.Format("{0:C}",ans).ToString();
}
56
EEES-403 - C#
Cukurova University
TaxApp Form
Tax calculator output
57
EEES-403 - C#
Cukurova University
A Form with One Button
• Using one of the 4 described techniques, we will add a Button to a new form.
• We will program a handler function that will respond to the Click event,
generated when the mouse is clicked while its pointer is positioned over the
button.
• This event is termed a Button.Click event.
58
EEES-403 - C#
Cukurova University
Another Items CheckBox
GroupBox
RadioButton
Panel
TextBox
ListBox
59
EEES-403 - C#
Cukurova University
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
60
EEES-403 - C#
Cukurova University
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
-
11
61
EEES-403 - C#
Cukurova University
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
62
EEES-403 - C#
Cukurova University
Radio Buttons
– Checked – get/set Boolean indicating if the button is checked
– CheckedChanged – delegate invoked when the button is
checked or unchecked
63
EEES-403 - C#
Cukurova University
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
64
EEES-403 - C#
Cukurova University
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
– 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
65
EEES-403 - C#
Cukurova University
Example
66
EEES-403 - C#
Cukurova University
Populating a ListBox
• Any object can be placed into a ListBox
• The display is generated by ToString()
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i < 50; i++)
{ listBox1.Items.Add("Item " + i.ToString()); }
}
OR
listBox1.Items.Add("Sunday");
listBox1.Items.Add("Monday");
listBox1.Items.Add("Tuesday");
listBox1.Items.Add("Wednesday");
listBox1.Items.Add("Thursday");
listBox1.Items.Add("Friday");
listBox1.Items.Add("Saturday");
-
12
67
EEES-403 - C#
Cukurova University
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
68
EEES-403 - C#
Cukurova University
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
• 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
69
EEES-403 - C#
Cukurova University
Example
70
EEES-403 - C#
Cukurova University
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
71
EEES-403 - C#
Cukurova University
DomainUpDown
• A DomainUpDown control allows users to provide a spin (up/down) interface to
move through pre-defined strings using up and down arrows.
• SelectedItemChanged event handler. Every time the selected item is changed
by the user, this code is executed.
72
EEES-403 - C#
Cukurova University
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
-
13
73
EEES-403 - C#
Cukurova University
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
74
EEES-403 - C#
Cukurova University
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
75
EEES-403 - C#
Cukurova University
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;
}
76
EEES-403 - C#
Cukurova University
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
77
EEES-403 - C#
Cukurova University
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
78
EEES-403 - C#
Cukurova University
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
• 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
-
14
79
EEES-403 - C#
Cukurova University
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
80
EEES-403 - C#
Cukurova University
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
81
EEES-403 - C#
Cukurova University
• Pls (screen shot, just codes), write the hw02 into doc file with give the name of you ID-HW02.doc(x) to mail to [email protected]
• Write a game program that
– Takes a number from user,
– Compares this number with generated random value between two given positive numbers
– User tries maximum3 times then if user knows says
• You Won OR
• You lost
• Write a program as a calculator with (*, /, +, -, % ) operators by using methods
– Check the values that are not 0(zero) or none numeric
– Write the result on screen with variables and operator
HOMEWORK-II Deadline : 22/11/2020 23:59
82
EEES-403 - C#
Cukurova University
The End ----Questions?
83
EEES-403 - C#
Cukurova University
References
• homepage.divms.uiowa.edu
These slides ae modified and copied from different slides especially from
• Telerik.com
• Prof. Roger Crawfis
http://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.html
• Programming C#, 4th Edition - Jesse Liberty – Chapt. 5
– Pls listen the podcast about the chapter 5 (Roger Crawfis)
– These slides are changed and modified
mailto:[email protected]://www.cse.ohio-state.edu/~crawfis/cse459_CSharp/index.htmlhttp://www.amazon.com/Programming-C-Building-NET-Applications/dp/0596006993/ref=pd_bbs_sr_1/105-4955683-2151618?ie=UTF8&s=books&qid=1192547778&sr=1-1