Windows Programming - EEMB DERSLER | Just … · 05/10/2010 · Windows Programming Form...
Transcript of Windows Programming - EEMB DERSLER | Just … · 05/10/2010 · Windows Programming Form...
11/24/2013
1
Windows Programming Form Programming II
2
Contents
Boxes-ListBox, ComboBox
Menus
TreeView
TabControl
Layout
MessageBox
File
Drawing
3
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
SelectedItem – the selected item
4
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
5
ListBox
Items – a collection of items in the list box
* see ListBoxDemo
6
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());
}
11/24/2013
2
7
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
8
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
9
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
* see ComboBoxDemo
10
Menus
Pulldown menus provide a way to select commands
and options
Normally these are in a MenuStrip across the top of
the application
Begin by placing a MenuStrip across the application
It displays boxes into which menu items and
cascading menus can be typed
11
Menus
The type here text allows
new items to be added
When you click on type
here a pull down appears
letting you select
Menu item
ComboBox
Separator
TextBox
12
MenuItem Properties
Checked – if true displays check mark
CheckOnClick – check state changes when clicked
CheckState – one of
CheckState.Checked
CheckState.Unchecked
CheckState.Indeterminate
ShortcutKeys – a member of the Shortcut enumeration indicating the shortcut key
11/24/2013
3
13
MenuItem
Click – event which is raised when the menu item is clicked
Menu items are similar to buttons and are handled in the same way
* see MenuDemo
14
ComboBox Menu Items
You can use a ComboBox as a menu item
Use the designer to add a set of Items to the combo box
You can then select a value
The click event is raised only when you click on the selected value, not when you change the selection
If you have nothing selected, the selected item will be null
15
TreeView
Presents a hierarchical tree view of the data
Nodes can be
Selected
Expanded and collapsed
Text of nodes can be edited
Nodes can be added or deleted programmatically
16
TreeView
This is the actual control
Properties
Nodes – get TreeNodeCollection of all children of this node
CheckBoxes – if true, displays checkboxes beside tree nodes
SelectedNode – the selected node
LabelEdit – if true, node text can be edited
17
TreeView
Events
AfterSelect – after a node is selected
AfterExpanded – after a node is expanded
AfterCollapsed – after a node is collapsed
AfterEdited – after a node is edited
18
Populating a TreeView
1. Usually, create a root TreeNode
2. Add the root node onto the Nodes collection of the TreeView
3. Create a child TreeNode and add it to the Nodes collection of the root node
4. Continue this way to build whole tree
11/24/2013
4
19
TreeViewEventArg
The signature for an event handler is
void EventHandler(object sender, EventArgs e)
TreeView events use a subclass called
TreeViewEventArg
Properties
Node – the node where the event originated
You will have to use the Node member to find which
tree node is affected by some events
* see TreeViewDemo 20
TabControl
Displays a series of tabs
Each tab is a different page with its own controls on it
Each tab is like a group box or panel
Create
In Visual Studio
Drop controls into the tab pages
Set the text property of every page to change the label
Right click on a tab and select “Add Tab” to add a new tab
21
TabControl
Multiline – if true tabs can be in several lines
SelectedIndex – index of selected tab
SelectedTab – the selected tab
TabPages – collection of TabPages
SelectedIndexChanged – event raised when a
different tab is selected
* see TabDemo
22
Automatic Layout
All of the forms we have seen so far have been laid out based on X-Y coordinates
If the outer form is resized, the contents stay at the same size and position
There are three ways to change this
The Dock property
The FlowLayoutPanel
The TableLayoutPanel
23
The Dock Property
Every control has a Dock property which can be set to
None – no docking
Left – docked to left side of container
Right – docked to right side of container
Top – docked to top of container
Bottom – docked to bottom of container
Fill – fills all available space
24
The Dock Property
When controls are docked to the
sides of their containing form,
resizing the form resizes the
controls inside as well
* see DockDemo
11/24/2013
5
25
FlowLayoutPanel
Arranges its contents into horizontal
or vertical rows
As form is resized, controls are
arranged into new rows or columns
Created in designer by dropping
controls into it
In designer it has small arrow on the
top that activates menu of editing
actions
26
FlowLayoutPanel
FlowDirection – layout direction
BottomUp
TopDown
LeftToRight
RightToLeft
WrapContents – whether the contents should be
wrapped to a new row or column or clipped
27
TableLayoutPanel
Arranges the controls within it into rows and columns
Automatically resizes contents when the surrounding form is resized
The pull-out menu in designer can be used to add or delete rows and columns
28
TableLayoutPanel
ColumnCount – get/set number of columns
RowCount – get/set number of rows
* see LayoutDemo
29
MessageBox
A pop-up dialog which displays a message
Use the static Show methods to see one
DialogResult Show(string) – box with simple string and OK button
DialogResult Show(string text, string caption)
DialogResult Show(string text, string caption, MessageBoxButtons)
OK
OKCancel
RetryCancel
YesNo
YesNoCancel
30
DialogResult
Abort
Cancel
Ignore
No
None
OK
Retry
Yes
*See DialogDemo; Calculator(NetCalc
11/24/2013
6
31
Files & Directories
This section will explore how to work with files and
directories
We begin with directories
Directory
Contains static methods for creating, deleting, moving and listing
directories
DirectoryInfo
An instance represents a directory
Has instance methods for manipulating the directory 32
Directory Class
Method Description
CreateDirectory( )
Creates all directories and subdirectories specified by its
path parameter.
GetCreationTime() Returns and sets the time the specified directory was
created.
GetDirectories() Gets named directories.
GetLogicalDrives() Returns the names of all the logical drives in the form
<drive>:\.
GetFiles() Returns the names of files matching a pattern.
GetParent() Returns the parent directory for the specified path.
Move() Moves a directory and its contents to a specified path.
33
Directory Class
Method Description
Delete( ) Deletes a directory.
Exists() Determines if a directory exists.
GetFiles() Returns the names of files in a specified directory.
GetCurrentDirectory() Returns the path of the current directory.
GetLastAccessTime() Returns the last time file was accessed.
GetLastWriteTime() Returns the last time file was written.
34
DirectoryInfoClass
Method Description
Attributes
Inherits from FileSystemInfo; gets or sets the
attributes of the current file.
CreationTime gets or sets the creation time of the current file.
Exists true if the directory exists.
Extension The File Extension
FullName the full path of the file or directory.
Name The directory name.
Root Root portion of the path.
Parent Parent Directory
35
DirectoryInfo Class
Method Description
Create() Creates the directory if it does not exist.
CreateSubdirectory() Creates a subdirectory.
Delete() Deletes the directory.
GetDirectories() Returns an array of DirectoryInfo objects.
GetFiles() Returns an array of FileInfo objects.
MoveTo() Relocates the directory and its contents.
Refresh() Refreshes the directory list.
36
A File Lister string curDirName = Directory.GetCurrentDirectory();
DirectoryInfo curInfo = new DirectoryInfo(curDirName);
Console.WriteLine("Listing for {0}", curInfo.FullName);
DirectoryInfo[] dlist = curInfo.GetDirectories();
foreach (DirectoryInfo d in dlist) {
Console.WriteLine("{0}\t\t{1}", d.Name, d.LastWriteTime);
}
FileInfo[] flist = curInfo.GetFiles();
foreach (FileInfo f in flist) {
Console.WriteLine("{0}\t\t{1}", f.Name, f.LastWriteTime);
}
11/24/2013
7
37
Working with Files
Two classes are provided to deal with files
File
A collection of static methods to manipulate files
FileInfo
Instance methods to manipulate a single file
These classes are analogous to the two directory classes
They add the ability to read and write files
38
Reading and Writing Files
Files can be read and written in two ways
Binary
Binary data is written to a file
Fast, efficient, not human readable
Suited for writing data structures
Text
Converts bytes to a specific character encoding
Slower than binary
Can be read by humans
* See CreatefileDemo, readsequentialaccessfile, fileTest
39
Stream Class
The Stream class is used to read and write binary data
from and to a file
Read methods
int Read(byte[] buf, int offset, int count)
Reads up to count bytes into buf at offset
Return the number of bytes read or zero at EOF
int ReadByte()
Reads one byte
Returns -1 at EOF 40
Stream Class
Write methods
void Write(byte[] buf, int offset, int count)
void WriteByte(byte);
void Flush();
Direct Access Methods
long Seek(long offset,seekOrigin);
41
SeekOrigin
An enumeration with values indicating where a seek should be from
Begin, Current, End
Seeking moves the read/write pointer through a file and determines where the next read or write will occur
42
StreamReader Class
This reads a file by converting the bytes to characters
int Read()
Reads the next char, returns -1 on EOF
int Read(char[] buf, int offset, int count)
Reads up to count chars into buf at offset
Return 0 at EOF
string ReadLine()
Reads the next line
Returns null on EOF
11/24/2013
8
43
StreamWriter Class
Used to write text files
void Write(char)
void Write(char[])
void Write(string)
Void Flush()
44
Buffered Streams
Read and writing a byte at a time is painfully slow
It is much more efficient to read and write a buffer full at a time
The BufferedStream class does just that
It works just like a stream
Just wrap it around your stream
BufferedStream bs = new
BufferedStream(stream);
45
Opening Binary Streams
Open one stream for reading and one for writing
Use the static methods of the File class
Stream OpenRead(string path);
Stream OpenWrite(string path);
46
Reading and Writing Text Files
To create a file for writing
StreamWriter sw = new
StreamWriter("MyFile.txt");
To open a file for reading
FileInfo fi = new
FileInfo("MyFile.txt");
StreamReader sr = fi.OpenText();
47
Reading and Writing Text Files
The following example
Checks to see if a file exists
If it does not, it opens the file for writing and
writes some content
It then opens the file for reading and writes the
contents to the console
It then closes the file
48
Drawing
So far, we have used controls to draw everything on the screen
There is a lower-level interface which can be used to draw anything into a form
Using this we can
Handle any type of event
Draw anything
Create our own controls
11/24/2013
9
49
Coordinates
All windows have their own coordinate
space with the origin in the top-left
corner
X values increase to the right
Y values increase downward
Coordinates are usually expressed as an
integer number of pixels
(0,0) X
Y
50
Measurement Units
Pixel is the default unit but others can be used
Graphics has a property PageUnit which is a member of the enum GraphicsUnit
Display – device units: pixels for monitors & 1/100 inch for printers
Document – 1/300 inch
Inch – inch
Millimeter – millimeter
Pixel – (default) pixel
Point – 1/72 inch
World – world coordinates
51
Drawing
We have already see the Color and Font classes
To draw we are also interested in
Pen – the width & color of a line
Brush – the fill for a figure like a rectangle
SolidBrush – a solid color
TextureBrush – a pattern
Graphics – a class containing drawing methods
52
Pen
A drawing object used to specify the color and width of a line
Constructor
Pen(Color, int width)
Pen(Brush, int width)
Properties
DashStyle – for dashed lines, one of
Solid
Dash
DashDot
DashDotDot
Dot
53
SolidBrush
A color used to fill the interior of a closed figure
Constructor
SolidBrush(Color)
Properties
Color – get/set the brush color
54
Graphics
The graphics object is associated with a drawing surface and provides methods to draw on that surface
The graphics object is given to you by the framework, you do not create it
11/24/2013
10
55
Graphics
Clear(Color) – clears the entire surface with the color
DrawArc(Pen, int x, int y, int ht, int
wd, int startAngle, int endAngle) – draw an arc of an ellipse contained by the rectangle
DrawEllipse(Pen, int x, int y, int ht,
int wd) – draw an ellipse within the rectangle
56
Graphics
DrawLine(Pen, Point, Point) – draw a line between two points
DrawPie(Pen, int x, int y, int
ht, int wd) – draw an pie slice within the rectangle
DrawRectangle(Pen, int x, int y,
int ht, int wd) – draw a rectangle
57
Graphics
DrawString(string, Font, Brush, single
x, single y) – draw a string at the point
FillMethods
Most of the draw methods have equivalent Fill methods
The Fill methods draw a solid figure rather than an outline
They use a brush rather than a pen
58
Event Handling
When you create your own control which draws you can
Add event handlers as we have done in the past
Override the methods for handling these events in the parent class
Often, it is easier to override the methods in the
parent class to make behaviour inheritable
59
Event Handling Methods
void OnMouseDown(MouseEventArgs e)
void OnMouseUp(MouseEventArgs e)
void OnMouseMove(MouseEventArgs e)
void OnMouseWheel(MouseEventArgs e)
void OnKeyDown(KeyEventArgs e)
OnKeyUp(KeyEventArgs e)
void OnResize(EventArgs e)
60
MouseEventArgs
Button – get button pressed
Clicks – get the number of times the button was pushed and released
Delta – number of positions mouse wheel rotated
X – mouse coordinate
Y – mouse coordinate
11/24/2013
11
61
Painting
Forms are painted by calling OnPaint(Graphics
g)
You override this method to paint whatever you need
You NEVER call this method
You call Invalidate() when you want to be
repainted and the windowing system calls
OnPaint() for you
62
Overriding Methods
When you override a method, your method is called, not the one in the parent class
However, the one in the parent class often does something important
Therefore, always call the method in the base class before doing your own thing
* see WinDraw