Professional Documents
Culture Documents
Lp trnh GUI
User interface modeling
User interface architecture
User interface coding
MyForm
Label
label1
Hell
button1
Button
OK
Internal structure
Form
Button
Form
containers
Panel
Panel
Label
Button
Label
Form
Mt form l mt ca s mn hnh - mt
n v giao din ngi dng do Microsoft
a ra k t Windows 1.0
Mt ng dng Windows Forms (WinForms)
phi c t nht mt ca s main form
(ca s chnh
Form c th cha cc component
Form c th c cc file resource
8
V d 1
class Program
{
static void Main(string[] args)
{
Form f = new Form();
Application.Run(f);
}
}
V d 2
class Program
{
static void Main(string[] args)
{
MessageBox.Show("Hello World");
}
}
10
Application class
Exit
Stops all running message loops and closes all windows in the
application. Note that this may not force the application to exit
Run
DoEvents
11
V d 3
public static void Main()
{
Form form1 = new Form();
Form form2 = new Form();
form1.Text = "Form passed to Run()";
form2.Text = "Second form";
form2.Show();
Application.Run(form1);
MessageBox.Show("Application.Run() has returned control
back to Main. Bye, bye!",
"TwoForms");
}
12
V d 3
13
Form Properties
Thuc tnh
Kiu
M t
FormBorderStyle FormBorderStyle:
FixedDialog,
Fixed3D
Kiu ng vin
ControlBox
bool
C system menu
box?
MaximizeBox
bool
MinimizeBox
Icon
ShowInTaskBar
bool
Icon
bool
StartPosition
FormStartPosition
14
Form Properties
Thuc tnh
Kiu
SizeGripStyle
WindowState
FormWindowState: Normal,
Maximized, Minimized
TopMost
Text
Size
bool
string
Point
ForeColor
Font
Location
color
font
Point
M t
15
Form Properties
Thuc tnh
Kiu
M t
AcceptButton
CancelButton
16
StartPosition - FormBorderStyle
V d 4
18
V d 4
static void Main(string[] args)
{
Form form = new Form();
form.Text = "Form Properties";
form.BackColor = Color.BlanchedAlmond;
form.Width *= 2;
form.Height /= 2;
form.FormBorderStyle = FormBorderStyle.FixedSingle;
form.MaximizeBox = false;
form.Cursor = Cursors.Hand;
form.StartPosition = FormStartPosition.CenterScreen;
Application.Run(form);
}
19
Form Method
Show()
ShowDialog();
Hide();
Close();
20
21
Form Event
Click
DoubleClick
KeyDown
MouseHover
Paint
Resize
22
23
Events
Mt event l mt i tng biu din mt hnh ng
V d:
The mouse is moved or button clicked
The mouse is dragged
A graphical button is clicked
A keyboard key is pressed
A timer expires
S kin thng tng ng vi thao tc ca ngi dng
C th vit cc b p ng s kin
User
GUI
Control
event
Event
handler
message
program
24
User
Event Handler:
{
Get N1 and N2
Return N1+N2
Call the program
}
Program:
Put N1+N2
25
Button
Event
Handler
Button
Event
Handler
Handler 1
GUI Control
Handler 2
GUI Control
Handler
GUI Control
Handler 3
calls Handler 1 for event E
calls
Object A raises event E
GUI Events
App1
mouse
click
OK
App2
OK
Cancel
Cancel
App2 code:
App1
event
loop
Window
System
input
device
event
loop
which
app?
App2
event
loop
which
control?
OKbtn_click()
{
do stuff;
}
CancelBtn_click()
{
do different stuff;
}
App2Form_click()
{
do other stuff;
27
}
GUI program
User input commands
Non-linear execution
Unpredictable order
Much idle time
GUI program:
main()
{
decl data storage;
initialization code;
create GUI;
register callbacks;
}
Callback1()
{
code;
}
Callback2()
{
code;
}
//button1 press
//button2 press
28
C# WinApp
C# WinApp:
delegates = callbacks
Function pointers
Listeners
Class{
decl data storage;
constructor(){
initialization code;
create GUI controls;
register callbacks;
}
main(){
Run(new )
}
callback1(){
do stuff;
}
callback2(){
do stuff;
}
29
Delegates
1. ng k control nhn events
1. button1.Click += button1_click( )
click
Button1
2. button1_Click( )
Button1_click()
callback 30
Event Handler
Thng ip gi i bng cch chuyn giao.
B x l s kin(Event Handler) s c
gi khi s kin tng ng pht sinh
void EventMethodName(Object sender, EventArgs e)
31
Paint Event
class Program
{
static void Main(string[] args)
{
Form f = new Form();
f.Click+=new EventHandler(f_Click);
Application.Run(f);
}
static void f_Click(Object sender, EventArgs e) {
Form f = (Form)sender;
Graphics gx = f.CreateGraphics();
gx.DrawString("Form 1 \n Form 1\n", f.Font, Brushes.Black, 30, 30);
}
}
32
Paint Event
class Program
{
static void Main(string[] args)
{
Form f = new Form();
f.Paint+=new PaintEventHandler(f_Paint);
Application.Run(f);
}
static void f_Paint(Object sender, PaintEventArgs e)
{
Form f = (Form)sender;
Graphics gx = f.CreateGraphics();
gx.DrawString("Form 1 \n Form 1\n", f.Font, Brushes.Black, 30, 30);
}
}
33
34
Thm control
static void Main(string[] args)
{
Form f1 = new Form();
Button b = new Button();
b.Text = "OK";
b.Click+=new EventHandler(b_Click);
b.Location = new Point(10, 10);
Button b1 = new Button();
b1.Text = "Exit";
b1.Click += new EventHandler(b1_Click);
b1.Location= new Point(b.Left, b.Height + b.Top + 10);
f1.Controls.Add(b);
f1.Controls.Add(b1);
f1.Text = "2 Paint Event";
f1.BackColor=Color.White;
f1.AcceptButton = b;
f1.CancelButton = b1;
Application.Run(f1);
}
35
Thm control
static void b_Click(Object sender, EventArgs e)
{
MessageBox.Show("Hello World");
}
static void b1_Click(Object sender, EventArgs e)
{
Application.Exit();
}
36
K tha Form
class Myform:System.Windows.Forms.Form
{
public Myform()
{
Text = "My Form Class";
}
}
K tha Form
class Myform:System.Windows.Forms.Form
{
public Myform()
{
Text = "My Form Class";
}
protected override void OnPaint(PaintEventArgs pea)
{
Graphics g=pea.Graphics;
g.DrawString("Hello World", Font, Brushes.Red,20,20);
}
}
38
K tha Form
class Program
{
static void Main(string[] args)
{
Myform f=new Myform();
f.Text = "Ke thua tu " + f.Text;
f.Paint+=new PaintEventHandler(f_Paint);
Application.Run(f);
}
static void f_Paint(Object sender, PaintEventArgs pea)
{
Form form = (Form)sender;
Graphics g = pea.Graphics;
g.DrawString("New Hello World", form.Font, Brushes.Red, 50, 50);
}
}
39
K tha Form
class Myform:System.Windows.Forms.Form
{
public Myform()
{
Text = "My Form Class";
}
protected override void OnPaint(PaintEventArgs pea)
{
base.OnPaint(pea);
Graphics g=pea.Graphics;
g.DrawString("Hello World", Font, Brushes.Red,20,20);
}
}
40
MessageBox.Show
MessageBox.Show (String strText)
MessageBox.Show (String strText, String strCaption)
MessageBox Buttons
Member
Value
Ok
OkCancel
AbortRetryIgnore
YesNoCancel
YesNo
RetryCancel
0
1
2
3
4
5
42
MessageBox Icon
Member
Value
None
0x00
Hand
0x10
Stop
0x10
Error
0x10
Question
0x20
Exclamation
0x30
Warning
0x30
Asterisk
0x40
Information
0x40
43
44
Form Controls
L n v c s to nn giao din ngi dng trong
lp trnh WinForm.
L bt k i tng no nm trong vng cha ca
Container c kh nng tng tc vi ngi s dng.
L i tng dng nhn d liu c nhp vo hoc
xut d liu trn window form
Cc control c cc c im, cc phng thc v cc
s kin ring cho control
45
Cc lp c s
System.Windows.Forms.Control -cha chc nng c bn ca thao
tc x l bn phm v nhp t chut v x l tin nhn window.
System.Windows.Forms.ButtonBase - Lp ny h tr chc nng c
bn ca mt nt
System.Windows.Forms.TextBoxBase - cung cp chc nng v thuc
tnh thng thung cho cc lp tha hng. C hai lp TextBox v
RichTextBox s dng chc nng cung cp bi TextBoxBase.
System.Windows.Forms.ScrollableControl - qun l s pht sinh v
hin th ca cc thanh cun n ngi dng truy cp n gc ca
mt hin th.
System.Windows.Forms.ContainerControl - Lp ny qun l chc
nng yu cu cho mt control hnh ng
System.Windows.Forms.Panel - c th cha cc control thm vo,
nhng khc vi lp ContainerControl, n phn loi cc control mt cch
n gin.
System.Windows.Forms.Form - To bt k loi ca s no: standard,
toolbox, borderless, modal dialog boxes v multi-document interfaces.
System.Windows.Forms.UserControl - to mt custom control n
vic c dng trong mt ni phc tp trong mt ng dng hay t chc
47
STANDARD CONTROL
Mt i tng control k tha trc tip/ gin tip t
System.Windows.Forms.Control
C cc loi:
Action control: Button, Toolbar, MenuBar,
ContextMenu
Value control: Label, TextBox, PictureBox
List control: ListBox, ComboBox, DataGrid, TreeView,
Container control: GroupBox, Panel, ImageList,
Dialogs:OpenFileDialog, SaveFileDialog,
PrintDialog, etc
48
Buttons
M t
Control
Button
CheckBox
RadioButton
M t
49
PictureBox
LinkLabel
M t
Visual grouping for sets of related controls
Text label, usually providing a name or description for
some other control (e.g., a text box)
A picture: supports various bitmap formats (BMP, ICO,
JPEG, TIFF, and PNG) and Windows metafiles
Hyperlink, e.g., a URL; this effectively combines labellike and button-like behavior
50
Text editing
Control
TextBox
RichTextBox
NumericUpDown
DomainUpDown
M t
An editable text field (plain text only)
An editable text fields supporting text with
formatting (based on RTFthe Rich Text Format)
A text box containing a number, and an associated
pair of up/down buttons (often known as a spin
control)
Similar to a NumericUpDown, only the text box can
contain any string; the up and down buttons move
through a list of strings
51
M t
A vertical list of selectable text items (items may also
have images)
An editable text field with an associated drop-down list
of selectable items
A list of selectable items similar to the contents of a
Windows Explorer window; supports Large Icon, Small
Icon, List and Details views
A hierarchical display, similar to that used in the Folders
pane of Windows Explorer
A UI for editing properties on some object; very similar
to the Properties panels in Visual Studio .NET
A grid control showing the contents of a DataSet
52
M t
A horizontal Windows scrollbar
A vertical Windows scrollbar
A UI for selecting from a linear range of values (useful
for continuous ranges such as percentages)
A bar indicating what proportion of a long-running task
has completed
53
Layout
Control
M t
TabControl
Splitter
StatusBar
ToolBar
54
Label
PROPERTIES
Methods
Image
TabStop
Events
Paint
55
TextBox
Methods
PROPERTIES
AcceptReturn
ReadOnly
Passwordchar
MaxLength
Multiline
ScrollBars
Events
Cut
Copy
TextChanged
56
Button
PROPERTIES
Methods
DialogResult
TextAlign
Events
57
ListBox control
ListBox control c dng hin th danh sch
cc phn t.
Ngi dng c th chn mt hay nhiu phn t
t list.
Bn c th thm phn t mi vo list thng qua
ca s property editor hoc l thng qua m
chng trnh lc chy.
Cc thuc tnh thng gp:
SelectionMode
Sorted
SelectedIndex
SelectedItem
58
ListBox [1]
PROPERTIES
Items
MultiColumn
SelectedItems
SelectedIndex
SelectedValue
SelectedItem
Sorted
Text
59
ListBox [2]
Methods
ClearSelected
GetSelected
FindString
SetSelected
Events
SelectedIndexChanged
SelectedValueChanged
60
CheckedListBox
PROPERTIES
CheckedIndices
ThreeDCheckBoxes
CheckedItems
Methods
SetItemChecked
GetItemChecked
Events
GetItemCheckState
SetItemCheckState
ItemCheck
61
ComboBox control
Dng hin th danh sch cc phn t, tuy
nhin ComboBox hin th cc danh sch ny theo
kiu drop down.
ComboBox c cho php ngi dng nhp d liu
vo.
Cc phn t trong ComboBox c th c thm
vo thng qua property editor hoc m chng
trnh lc chy.
Mt s cc thuc tnh thng dng:
Text
Sorted
SelectedIndex
SelectedItem
62
ComboBox
Methods
PROPERTIES
DropDownStyle
Select
Focused
SelectAll
MaxDropDownItems
Events
DropDown
63
CheckBox control
CheckBox control dng hin th Yes/No
hay ng/sai.
64
RadioButton control
Dng cho ngi dng chn mt la
chn.
Text
Checked
65
KiU TRNH BY NG
Anchoring
66
KiU TRNH BY NG
Docking
67
LAYOUT CONTROLS
SplitContainer
68
LAYOUT CONTROLS
FlowLayout
69
LAYOUT CONTROLS
TableLayoutPanel
70
1: using System;
2: using System.Windows.Forms;
3: using System.Drawing;
4: 5: namespace TYWinforms.Day2 {
6: 7: public class Calculator : Form {
8: private Button btnAdd;
9: private TextBox tbNumber1;
10: private TextBox tbNumber2;
11: private Label lblAnswer;
12: 13: public static void Main() {
14: Application.Run(new Calculator());
15: }
16: 17: public Calculator() {
18: this.btnAdd = new Button();
19: this.tbNumber1 = new TextBox();
20: this.tbNumber2 = new TextBox();
21: this.lblAnswer = new Label();
22: 23: tbNumber1.Location = new Point(0,0);
24: tbNumber2.Location = new Point(100,0);
25: 26: btnAdd.Location = new Point(0,25);
71
72
3.MENU
73
Menu
Nhm cc lnh lin quan vi nhau
Gm:
Commands
Submenus
74
Menu
Menu
Shortcut
key
Disabled
command
submenu
Separator bar
Checked
menu
item
75
RightToLeft
76
Index
MenuItems
MergeOrder
MergeType
77
Menu Constructors
MainMenu();
MainMenu(Menultem[] ami);
FormName.Menu = mMenu
ContextMenu()
ContextMenu(Menultem[] ami)
FormName.ContextMenu = cMenu
MenuItem()
Menultem(string strText)
Menultem(string strText, EventHandler ehClick)
Menultem(string strText, EventHandler ehClick, Shortcut sc)
Menultem(string strText, Menultem[] ami)
mMenu.MenuItems.Add(miItem)
cMenu. .MenuItems.Add(miItem)
79
class MenuForm:Form
{
MainMenu mMenu;
MenuItem mFile;
MenuItem miFileOpen;
public MenuForm()
{
mMenu = new MainMenu();
mFile=new MenuItem();
mFile.Text="File";
miFileOpen = new MenuItem();
miFileOpen.Text = "Open";
miFileOpen.Click+=new EventHandler(miFileOpen_Click);
mFile.MenuItems.Add(miFileOpen);
mMenu.MenuItems.Add(mFile);
this.Menu = mMenu;
}
void miFileOpen_Click(Object sender, EventArgs ea)
{
MessageBox.Show("Menu Open Click");
}
}
80
class MenuForm:Form
{
MainMenu mMenu;
MenuItem mFile;
MenuItem miFileOpen;
public MenuForm()
{
miFileOpen = new MenuItem("Open",
new EventHandler(miFileOpen_Click),
Shortcut.CtrlO);
mFile = new MenuItem("File", new MenuItem[] { miFileOpen});
mMenu = new MainMenu(new MenuItem[] { mFile });
this.Menu = mMenu;
}
void miFileOpen_Click(Object sender, EventArgs ea)
{
MessageBox.Show("Menu Open Click");
}
}
81
class MenuForm:Form
{
MainMenu mMenu;
MenuItem mFile;
MenuItem miFileOpen;
MenuItem mExit;
public MenuForm()
{
miFileOpen = new MenuItem("Open",
new EventHandler(miFileOpen_Click),
Shortcut.CtrlO);
mFile = new MenuItem("File", new MenuItem[] { miFileOpen});
mExit = new MenuItem("Exit", new EventHandler(mExit_Click),
Shortcut.CtrlX);
mMenu = new MainMenu(new MenuItem[] { mFile,mExit });
this.Menu = mMenu;
}
void miFileOpen_Click(Object sender, EventArgs ea) {}
void mExit_Click(Object sender, EventArgs ea)
{ Application.Exit(); }
}
82
83
85
Bi tp
87
88
89
public CheckAndRadioCheck()
{
Text = "Check and Radio Check";
ResizeRedraw = true;
string[] astrColor = {"Black", "Blue", "Green", "Cyan",
"Red", "Magenta", "Yellow", "White"};
MenuItem[] ami = new MenuItem[astrColor.Length + 2];
EventHandler ehColor = new EventHandler(MenuFormatColorOnClick);
for (int i = 0; i < astrColor.Length; i++)
{
ami[i] = new MenuItem(astrColor[i], ehColor);
ami[i].RadioCheck = true;
}
miColor = ami[0];
miColor.Checked = true;
ami[astrColor.Length] = new MenuItem("-");
miFill = new MenuItem("&Fill, new EventHandler(MenuFormatFillOnClick));
ami[astrColor.Length + 1] = miFill;
MenuItem mi = new MenuItem("&Format", ami);
Menu = new MainMenu(new MenuItem[] { mi });
}
90
91
DIALOG
93
GII THIU
Dialog l 1 Windows Form c bit dng
tng tc vi ngi s dng v cung
cp cc thng bo.
Dialog l mt Windows Form a nng.
Dialog chnh l 1 Form vi thuc tnh
FormBorderStyle c gi tr FixedDialog
94
GII THIU
Mc ch s dng chnh ca Dialog l trao i
thng tin vi ngi s dng.
Sau khi ly c thng tin, trnh x l ca
Dialog s ly thng tin thc hin mt cng
vic khc.
95
CC DIALOG PH BiN
ColorDialog
FontDialog
OpenFileDialog
PageSetupDialog
PrintDialog
PrintPreviewDialog
SaveFileDialog
97
98
100
101
102
103
104
TO MI DIALOG
Cc Dialog c sn khng th p ng ht
nhu cu ca ngi s dng.
To mi Dialog tng t nh to 1 form
Khng cha phng thc Main()
105
V d 1
107
class SimpleDialogBox:Form
{
public SimpleDialogBox()
{
Text = "Simple Dialog Box;
FormBorderStyle = FormBorderStyle.FixedDialog;
ControlBox = false; MaximizeBox = false;
MinimizeBox = false;ShowInTaskbar = false;
Button btn = new Button();
btn.Parent = this;
btn.Text = "OK";
btn.Location = new Point(50, 50);
btn.Size = new Size(10 * Font.Height, 2 * Font.Height);
btn.Click += new EventHandler(ButtonOkOnClick);
btn = new Button();
btn.Parent = this;
btn.Text = "Cancel";
btn.Location = new Point(50, 100);
btn.Size = new Size(10 * Font.Height, 2 * Font.Height);
btn.Click += new EventHandler(ButtonCancelOnClick);
}
Phin
bn
0.1
108
Phin
bn
0.1
109
class SimpleDialogBox:Form
{
public SimpleDialogBox()
{
Text = "Simple Dialog Box;
FormBorderStyle = FormBorderStyle.FixedDialog;
ControlBox = false; MaximizeBox = false;
MinimizeBox = false;ShowInTaskbar = false;
Button btn = new Button();
btn.Parent = this;
btn.Text = "OK";
btn.Location = new Point(50, 50);
btn.Size = new Size(10 * Font.Height, 2 * Font.Height);
btn.DialogResult = DialogResult.OK;
btn = new Button();
btn.Parent = this;
btn.Text = "Cancel";
btn.Location = new Point(50, 100);
btn.Size = new Size(10 * Font.Height, 2 * Font.Height);
btn.DialogResult = DialogResult.Cancel;
}
}
Phin
bn
0.2:
Dng
Property
DialogResult
111
V d
112
Modeless Dialog
113