Professional Documents
Culture Documents
Chuong3 Windowsforms 110824083459 Phpapp02
Chuong3 Windowsforms 110824083459 Phpapp02
Windows Forms
Ni dung
Lp trnh C# trn Windows To ng dng Windows Forms t u To ng dng Windows Forms t Wizard Tng quan cc i tng trong Windows Forms Lp Application Lp Form Cc Control thng dng
Label, LinkLabel, Textbox, Button Checkbox, CheckboxList, RadioButton PictureBox v Bitmap
Ni dung
B cc control Panel Anchor Dock Splitter MessageBox Cc dialog thng dng Custom Form
Truyn d liu cho form bng tham s Truyn d liu cho form bng property
Ni dung
Menu: MenuStrip, ContextMenuStrip StatusStrip, ToolStrip, ToolStripContainer ng dng SDI, MDI Modal Form Modeless Form Cc Dialog thng dng Mouse v Keyboard
Hng i h thng
Message loop
Nhn v x l
ng dng B
Hm Window Procedure
Mi ca s (Window) trong Application u c mt hm Window procedure x l cc message do message loop nhn v
Dispatched messages
Retrieved messages
WM_KEYDOWN
OnKeyDown
WM_MOUSEMOVE
WM_PAINT Messages Message queue
OnMouseMove
Message loop
OnPaint
Window procedure
10
Message queue: Cc message c ch trong message queue cho n khi chng c nhn x l
11
12
Event driven programming model trong C# Message Loop Application.Run() Window Form Window Procedure WndProc(ref Message m) Phn ln cc Message handlers c ci t sn trong cc lp c th nhn message (Control, Form, Timer, ) di dng cc hm protected: protected void OnTenMessage(xxxEventArgs e)
xxxEventArgs c th l EventArgs hay cc lp con ca EventArgs
Mi message c mt bin event tng ng. Cc Message handlers mc nhin gi cc event tng ng ca message Cc hm gn cho event gi l event handler
13
Dispatched messages
Retrieved messages
WM_KEYDOWN
OnKeyDown
WM_MOUSEMOVE
WM_PAINT Messages Message queue
OnMouseMove
Application.Run()
OnPaint
WndProc(ref Message m)
14
Cc bc c bn to ng dng Windows
Bc 1:
Thit k giao din
Bc 2:
X l cc message do Windows gi n
Bc 3:
X l nghip v
16
Cc bc c bn to ng dng Windows
X l cc thng ip do Windows gi n: bng cch override cc message handler X l cc nghip v trn cc message handler
17
Cc bc c bn to ng dng Windows
Bt cc s kin: bng cch vit cc event handler X l nghip v trn cc event handler
18
Cc bc c bn to ng dng Windows
Bc 1: To Empty Project
File New Project Project Type: Visual C# Windows Template: Empty Project
Bc 2: Thm references
Click phi ln References Add Reference...
System.Windows.Forms System.Drawing [System.Core]
19
class Program { static void Main() { Form form = new Form(); form.Text = First Application; Application.Run(form); }
20
Thuc tnh
class Program { static void Main() { Form form = new Form(); form.Text = "WinForm"; form.BackColor = Color.Green; form.Width = 300; form.Height = 300; form.MaximizeBox = false; form.Cursor = Cursors.Hand; form.StartPosition = FormStartPosition.CenterScreen; Application.Run(form); } }
21
Event Handler
class Program { static void Main() { Form form = new Form(); form.Text = WinForm; form.Click += form_Click; Application.Run(form); }
25
Bc 1: To Empty Project
File New Project Project Type: Visual C# Windows Template: Windows Forms Application
29
Solution Windows
Properties Windows
Toolbox
30
31
Bc 3: Thit lp cc Property cho cc i tng trn form thng qua Properties Windows
Properties Events Object Drop-Down Hin th theo loi Hin th theo vn
33
34
Lp Program
35
Lp MainForm
36
37
Cu trc ca ng dng
39
Lp Application
Namespace
System.Windows.Form
Assembly
System.Windows.Form (System.Windows.Form.dll)
41
Application Properties
public sealed class Application { // Properties public static string CommonAppDataPath { get; } public static RegistryKey CommonAppDataRegistry { get; } public static string CompanyName { get; } public static CultureInfo CurrentCulture { get; set; } public static InputLanguage CurrentInputLanguage { get; set;} public static string ExecutablePath { get; } public static string LocalUserAppDataPath { get; } public static bool MessageLoop { get; } public static FormCollection OpenForms {get; } public static string ProductName { get; } public static string ProductVersion { get; } public static bool RenderWithVisualStyles { get; } public static string SafeTopLevelCaptionFormat { get; set; } public static string StartupPath { get; } public static string UserAppDataPath { get; } public static RegistryKey UserAppDataRegistry { get; } public static bool UseWaitCursor { get; set; } public static VisualStyleState VisualStyleState { get; set; } } 42
Application Methods
public sealed class Application { // Methods public static void AddMessageFilter(IMessageFilter value); public static void DoEvents(); public static void EnableVisualStyles(); public static void Exit(); public static void ExitThread(); public static bool FilterMessage(ref Message message); public static ApartmentState OleRequired(); public static void RaiseIdle(EventArgs e); public static void RegisterMessageLoop(MessageLoopCallback callback); public static void RemoveMessageFilter(IMessageFilter value); public static void Restart(); public static void Run(); public static void Run(ApplicationContext context); public static void Run(Form mainForm); public static void UnregisterMessageLoop(); public static void SetCompatibleTextRenderingDefault(bool defaultValue); }
43
Application Events
public sealed class Application { // Events public static event EventHandler ApplicationExit; public static event EventHandler EnterThreadModal; public static event EventHandler Idle;
public static event EventHandler LeaveThreadModal; public static event ThreadExceptionEventHandler ThreadException public static event EventHandler ThreadExit; }
44
Application
45
Application
46
Application
V d
class MainForm:Form { private Button btnClose; public MainForm() { btnClose = new Button(); btnClose.Click += btnClose_Click; this.Controls.Add(btnClose); } private btnClose_Click(object sender, EventArgs e) { Application.Exit(); } }
47
Application
Bi tp luyn tp
Tm ng dn n file .exe Tm ng dn n th mc cha file .exe Shutdown ng dng v T ng restart li Thc hin nhng cng vic khi ng dng rnh ri Hin Cursor dng Wait khi ng dng ang bn thc thi cng vic X l trng hp mt phng thc thc thi mt nhiu thi gian
48
.NET Component
Namespace:
System.ComponentModel
Assembly
System (System.dll)
50
Cc Component khng h tr tng tc vi ngi dng bng form giao din t nhin
.NET Component Lp
public class Component : MarshalByRefObject, IComponent, IDisposable { // Events public event EventHandler Disposed; // Methods public Component(); public void Dispose(); protected virtual void Dispose(bool disposing); protected override void Finalize(); protected virtual object GetService(Type service); public override string ToString(); // Properties protected virtual bool CanRaiseEvents { get; } public IContainer Container { get; } protected bool DesignMode { get; } protected EventHandlerList Events { get; } public virtual ISite Site { get; set; } }
53
Control
Namespace
System.Windows.Forms
Assembly
System.Windows.Forms (System.Windows.Forms.dll)
55
56
Control S tha k
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ButtonBase System.Windows.Forms.DataGrid System.Windows.Forms.DataGridView System.Windows.Forms.DateTimePicker System.Windows.Forms.GroupBox System.Windows.Forms.Label System.Windows.Forms.ListControl System.Windows.Forms.ListView System.Windows.Forms.MdiClient System.Windows.Forms.MonthCalendar System.Windows.Forms.PictureBox System.Windows.Forms.PrintPreviewControl System.Windows.Forms.ProgressBar System.Windows.Forms.ScrollableControl System.Windows.Forms.ScrollBar System.Windows.Forms.Splitter System.Windows.Forms.StatusBar System.Windows.Forms.TabControl System.Windows.Forms.TextBoxBase System.Windows.Forms.ToolBar System.Windows.Forms.TrackBar System.Windows.Forms.TreeView System.Windows.Forms.WebBrowserBase
57
Control Events
public class Control : Component, ... { // Events // Property thay doi public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler }
AutoSizeChanged; BackColorChangedanged BackgroundImageCyoutChanged BackgroundImageLayoutChanged; BindingContextChanged; CausesValidationChanged; ClientSizeChanged; ContextMenuChanged; ContextMenuStripChanged; CursorChanged; DockChanged; EnabledChanged;
58
Control Events
public class Control : Component, ... { // Events // Property thay doi public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler public event EventHandler }
59
FontChanged; ForeColorChanged; LocationChanged; RegionChanged; ParentChanged; RightToLeftChanged; SizeChanged; TabIndexChanged; TabStopChanged; TextChanged; VisibleChanged;
Control Events
public class Control : Component, ... { // Events // Focus public event public event public event public event public event public event }
EventHandler Enter; EventHandler Leave; EventHandler GotFocus; EventHandler LostFocus; EventHandler Validated; CancelEventHandler Validating;
60
Control Events
public class Control : Component, ... { // Events // Key public public public public
// Mouse public event public event public event public event public event public event public event }
MouseEventHandler MouseDown; EventHandler MouseEnter; EventHandler MouseHover; EventHandler MouseLeave; MouseEventHandler MouseMove; MouseEventHandler MouseUp; MouseEventHandler MouseWheel;
61
Control Events
public class Control : Component, ... { // Events // Appearance public event InvalidateEventHandler Invalidated; public event PaintEventHandler Paint; // Layout public event public event public event public event public event // DragDrop public event public event public event public event public event public event }
62
LayoutEventHandler Layout; EventHandler MarginChanged; EventHandler Move; EventHandler PaddingChanged; EventHandler Resize;
DragEventHandler DragDrop; DragEventHandler DragEnter; EventHandler DragLeave; DragEventHandler DragOver; GiveFeedbackEventHandler GiveFeedback; QueryContinueDragEventHandler QueryContinueDrag;
Control Events
public class Control : Component, ... { // Events // Behavior public event public event public event public event public event public event
UICuesEventHandler ChangeUICues; ControlEventHandler ControlAdded; ControlEventHandler ControlRemoved; HelpEventHandler HelpRequested; EventHandler ImeModeChanged; QueryAccessibilityHelpEventHandler QueryAccessibilityHelp; public event EventHandler StyleChanged; public event EventHandler SystemColorsChanged; }
63
Control Events
public class Control : Component, ... { // Events // Action public event public event public event public event public event
EventHandler Click; EventHandler DoubleClick; EventHandler MouseCaptureChanged; MouseEventHandler MouseClick; MouseEventHandler MouseDoubleClick;
64
Control Methods
public class Control : Component, ... { // Mot so Methods public void Show(); public void Hide(); public bool Focus(); public Graphics CreateGraphics(); public void DrawToBitmap(Bitmap bitmap, Rectangle targetBounds); public void BringToFront(); public void SendToBack(); public Point PointToClient(Point p); public Point PointToScreen(Point p); public Rectangle RectangleToClient(Rectangle r); public Rectangle RectangleToScreen(Rectangle r); protected virtual void WndProc(ref Message m); protected virtual void OnClick(EventArgs e) }
65
Control Properties
public class Control : Component, ... { // Mot so properties // Layout public virtual Anchor { get; set; } public virtual DockStyle Dock { get; set; } public virtual bool AutoSize { get; set; } public Rectangle ClientRectangle { get; } public Size ClientSize { get; set; } public int Height { get; set; } // Appearance public virtual public virtual public virtual public virtual public virtual }
Color BackColor { get; set; } Image BackgroundImage { get; set; } Cursor Cursor { get; set; } Font Font {get; set; } Color ForeColor { get; set; }
66
Lp MessageBox
Lp MessageBox
Message Box hin mt thng bo hay mt hng dn cho user Lp MessageBox ch cha mt phng thc tnh duy nht: Show()
DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options);
Namespace
System.Windows.Forms
Assembly
System.Windows.Forms (System.Windows.Forms.dll)
68
Lp MessageBox
Cc Enumerations
MessageBoxButtons MessageBoxIcon MessageBoxDefaultButton MessageBoxOptions DialogResult
public enum MessageBoxIcon { Asterisk = 0x40, public enum MessageBoxButtons Error = 0x10, { Exclamation = 0x30, OK, Hand = 0x10, OKCancel, Information = 0x40, AbortRetryIgnore, None = 0, YesNoCancel, Question = 0x20, YesNo, Stop = 0x10, RetryCancel Warning = 0x30 } }
69
Lp MessageBox
public enum MessageBoxOptions { DefaultDesktopOnly = 0x20000, RightAlign = 0x80000, RtlReading = 0x100000, ServiceNotification = 0x200000 } public enum { Button1 Button2 Button3 } MessageBoxDefaultButton = 0, = 0x100, = 0x200
70
Lp MessageBox
public enum DialogResult { None, OK, Cancel, Abort, Retry, Ignore, Yes, No }
71
Lp Form
Lp Form th hin mt ca s (window) hay mt dialog box to nn giao din ca ng dng Thng thng to custom form bng cch tha k t lp Form Namespace
System.Windows.Form
Assembly:
System.Windows.Form (System.Windows.Form.dll)
73
Lp Form S tha k
System.Object System.MarshalByRefObject System.ComponentModel.Component System.Windows.Forms.Control System.Windows.Forms.ScrollableControl System.Windows.Forms.ContainerControl System.Windows.Forms.Form
74
Lp Form S tha k
public class Form : ContainerControl { // Methods public void public void public void public void Activate(); AddOwnedForm(Form ownedForm); Close(); LayoutMdi(MdiLayout value);
// Properties public bool ShowIcon { get; set; } public bool ShowInTaskbar { get; set; } public Size Size { get; set; } public FormStartPosition StartPosition { get; set; } // Events public event EventHandler Closed; public event CancelEventHandler Closing; public event EventHandler Deactivate; // Mics protected override void DefWndProc(ref Message m); protected override void WndProc(ref Message m); protected override void Dispose(bool disposing);
75
Lp Form Properties
76
Lp Form Properties
77
Lp Form Events
78
Lp Form Events
79
Lp Form Methods
To custom form
Click phi ln project trong solution Chn Add Windows Forms Cho custom form tha k t lp Form
Modeless Form
formName.Show ();
82
Nt OK v Cancel
Trc khi c th nhn d liu t Form ang hin th, phng thc ShowDialog() phi tr v, c ngha l form phi ng li Xc nh button no nhn (OK hay Cancel, ) chng ta dng property DialogResult
83
Nt OK v Cancel
Cch 1
private void btnOK_Click(object sender, EventArgs e) { this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); }
84
Nt OK v Cancel
Nhn xt
Khi gi phng thc Close() th phng thc ShowDialog() mc nhin s tr v DialogResult.Cancel (cng l gi tr ca property DialogResult) Chng ta c th tr v cc gi tr khc ca enum DialogResult
enum DialogResult { Abort, Cancel, // kt qu mc nhin khi gi Form.Close() Ignore, No, None, OK, Retry, Yes }
85
Nt OK v Cancel
Nhn xt
Kim tra gi tr tr v t phng thc ShowDialog() l cch nhanh nht kim tra gi tr ca thuc tnh DialogResult Hai on m sau l tng ng
dlg.ShowDialog(); DialogResult res = dlg.DialogResult; if (res == DialogResult.OK) {
}
if (dlg.ShowDialog() == DialogResult.OK) { }
86
Nt OK v Cancel
Cch 2
private void btnOK_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); }
Ch :
-Nt OK khng phi phm mc nhin -Nt Cancel khng c gi khi phm ESC nhn -Nt Enter khng c gi khi phm Enter nhn -Khi gn thuc tnh DialogResult th khng cn gi phng thc Close()
87
Nt OK v Cancel
Gn phm Enter/ESC cho nt OK/Cancel
Dng Designer thit lp 2 thuc tnh ca form: AcceptButton v CancelButton
private void InitializeComponent() { this.AcceptButton = this.btnOK; this.CancelButton = this.btnCancel; }
88
Nt OK v Cancel
Cch 3: (Dng Designer)
Thit lp property DialogResult ca nt OK: DialogResult.OK Thit lp property DialogResult ca nt Cancel: DialogResult.Cancel Trn form
Thit lp property AcceptButton: btnOK Thit lp property CancelButton: btnCancel
89
Nt OK v Cancel
Cch 3: (Dng Designer)
private void InitializeComponent() { this.btnOK.DialogResult = DialogResult.OK; this.btnCancel.DialogResult = DialogResult.Cancel; this.AcceptButton = this.btnOK; this.CancelButton = this.btnCancel; }
90
92
93
94
95
Lp Form
Bi tp luyn tp
Hy hin ra mt messagebox xc nhn user mun ng form Hin form gia mn hnh Khng cho user thay i kch thc form Khng cho form hin trong taskbar Hin form ph c mn hnh (bao gm taskbar) To form kiu splash screen Thay i icon ca form
96
Anchor: Ch ra cc cnh ca container bit control s thay i kch thc nh th no khi cha n thay i kch thc
Cc cnh ca container
Left, Top, Right, Bottom
98
99
101
Text Control
102
Label
Label control dng cung cp chui m t cho control Mt s property thng dng Text, TextAlign Image, ImageAlign, Visible BackColor, ForeColor Font Mt s phng thc thng dng Hide(), Show() Mt s event thng dng Paint
103
TextBox
104
TextBox
AutoCompleteSource
RecentlyUsedList HistoryList AllUrl = RecentlyUsedList + HistoryList ListItems
AutoCompleteMode
Append Suggest SuggestAppend
105
TextBox
Vit code
AutoCompleteStringCollection data = new AutoCompleteStringCollection(); data.Add(Le"); data.Add(Tran"); data.Add(Nguyen"); cb.AutoCompleteCustomSource = data;
106
TextBox
Bi tp luyn tp
Hy ngn cn
menu context khi click phi ln textbox Phm Ctrl+V
Textbox t ng chuyn thnh ch hoa hay ch thng khi nhp liu Dng Textbox nhp password Hy gii hn s k t trong Textbox Hy focus n control tip theo khi nhn enter
107
LinkLabel
108
LinkLabel
Bi tp luyn tp
Hy to form About gii thiu v chng trnh, c cc hyperlink trn
109
Status Bar
Cng dng:
Hin tnh trng hin ti ca ng dng
110
Button
111
Button
112
Button
To Access Key
buttonName.Text = &Print;
113
Button
Bi tp luyn tp
Thay i text ca button
Thay i text ca mt button v thay i chc nng tng ng
114
Button
Bi tp luyn tp
Lm th no click button bng lp trnh Lm th no pht sinh s kin click ca button trong nhng khong thi gian khi mouse ang click ln button c (ging scrollbar button) Lm th no t nh hay icon ln button
115
CheckBox v RadioButton
CheckBox
Properties
Text ch hin k bn checkbox Checked
Checked = true check box c check Checked = false check box cha c check
Events
CheckedChanged s kin pht sinh khi thay i trng thi check
117
CheckBox
118
Radio Buttons
119
Radio Buttons
120
List Controls
List Controls
C 3 list controls
ListBox CheckedListBox ComboBox
Lp c s: tha k t
lp tru tng ListControl
122
List Controls
Properties
Items danh sch cc item c trong list Sorted = true: t ng sp xp theo t in SelectedIndex, SelectedIndices, SelectedItem, SelectedItems v Text cung cp cc cch khc nhau truy cp cc mc chn
Methods
int FindString(string s) tm chui s c trong list hay khng
Events
SelectedIndexChanged
123
List Controls
124
ListBox
Properties
MultiColumn chia list thnh cc ct khi d liu khng hin th ht mt lc trn list SelectionMode quy nh ch chn cc mc trong list TopIndex Cun ListBox n TopIndex Methods
void ClearSelected() bool GetSelected(int index) void SetSelected(int index, bool value)
125
ComboBox=LISTBOX+TEXTBOX
ComboBox control cho php hin th danh sch cc mc dng drop down user chn Properties
MaxDropDownItems, DropDownStyle
Methods
void Select(int start, int length) void SelectAll()
Events
DropDown
126
CheckedListBox
Properties
CheckedItems v CheckedIndices truy cp mc chn MultiColumn chia list thnh cc ct khi d liu khng hin th ht mt lc trn list SelectionMode quy nh ch chn cc mc trong list TopIndex Cun CheckedListBox n TopIndex
127
CheckedListBox
Methods
void ClearSelected() bool GetSelected(int index) void SetSelected(int index, bool value) bool GetItemChecked(int index) CheckState GetItemCheckState(int index) void SetItemChecked(int index, bool value) void SetItemCheckedState(int index, CheckState value)
Events
ItemCheck
128
CheckedListBox
129
List Controls
Bi tp luyn tp
Lm th no check hay unchecked tt c cc mc trong CheckListBox Lm th no mc nhin chn item u tin trong ComboBox Cun Listbox hay ChecklistBox sao cho thy c mc va mi thm gn nht
130
Data binding
V d:
string[] cityChoices = { "Seattle", "New York", "Signapore", "Montreal"}; lstCity.DataSource = cityChoices;
131
Data binding
Items trong list control l mt tp cc object. Ch : hin th item trong trong list, list
control gi phng thc ToString()
C th kt hp cc i tng thuc cc lp t to vi list control
132
ImageList
ImageList
ImageList l mt kiu collection c bit cha cc nh c kch thc v su mu c xc nh trc. Cc control khc nu c h tr dng ImageList th dng cc nh trong ImageList thng qua ch mc.
ListView, TreeView, ToolBar, Button,
Properties
Images collection cc nh ImageSize kch thc ca cc nh TransparentColor nh ngha mu trong sut
Method
Draw() V nh ln b mt GDI+
134
ImageList
135
ImageList
136
ImageList
ImageList iconImages = new ImageList(); // Cu hnh ImageList iconImages.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; iconImages.ImageSize = new System.Drawing.Size(16, 16); // Ly cc file trong th mc hin ti string[] iconFiles = Directory.GetFiles(Application.StartupPath, "*.ico"); // Thm vo ImageList foreach (string iconFile in iconFiles) { Icon newIcon = new Icon(iconFile); iconImages.Images.Add(newIcon); }
137
ListView v TreeView
ListView
139
ListView
140
ListView
141
ListView
142
ListView
Properties Items Mt collection cc i tng ListViewItem c hin th trong ListView Columns Mt collection cc i tng ColumnHeader c dng trong Details View SelectedItems, SelectedIndices LargeImageList = imageList object SmallImageList = imageList object MultiSelect = bool View: LargeIcon, SmallIcon, List, Details, Tile Sorting = Acending/Descending FullRowSelect = bool
143
ListView
Methods
ListViewItem GetItemAt(int x, int y) ly item ti (x,y) void Clear() Xa cc item v cc ct
Events
ColumnClick, ItemCheck
144
ListView
Thm mt item n gin ListViewItem item = new ListViewItem(string); listView.Items.Add(item); Thm item c nh To imagelist Gn imagelist cho LargeImageList/SmallImageList item.ImageIndex=ch s hnh trong imagelist Thm item c nhiu subitem string[] data = {string1, string2, }; ListViewItem item = new ListViewItem(data); listView.Items.Add(item);
145
ListView
To detail
View: Detail GridLines: true Columns: Thm cc column
146
ListView
147
ListView
Thay i View
listView.View = View.SmallIcon
SmallIcon LargeIcon Details List Tile
148
ListView
Mt s properties khc
AllowColumnReorder AutoArrange CheckBoxes, CheckedIndices, CheckedItems GridLines
Mt s methods khc
BeginUpdate(), EndUpdate()
149
TreeView
150
TreeView
Properties
Nodes SelectedNode, ShowRootLines , ImageIndex, ShowPlusMinus
Methods
ExpandAll(), GetNodeAt(), GetNodeCount(), CollapseAll()
Events
AfterCheck, AfterCollapse, BeforeCheck, BeforeCollapse, AfterSelect, AfterExpand, BeforeSelect, BeforeExpand
151
TreeView
Thm mt node
Cch 1: tree.Nodes.Add(string); Cch 2:
TreeNode newNode = new TreeNode(); newNode.Text = "; newNode.Tag = "; tree.Nodes.Add(newNode);
152
TreeView
Cu trc TreeView
Cc nodes c th lng nhiu cp Thm node con:
Tm node cha Thm node con vo node cha
153
TreeView
Cu trc TreeView
V d 2: TreeNode[] nodes = new TreeNode[n]; nodes[0] = new TreeNode(cha); nodes[0].Nodes.Add(con); tree.Nodes.AddRange(nodes); V d 3: tree.BeginUpdate(); tree.EndUpdate();
154
TreeView
155
TreeView
156
TreeView
157
TreeView
158
TreeView
Node nh
nh cho ton TreeView
tree.ImageList = imageList; tree.ImageIndex = v tr
159
TreeView
Expand v collaps
Tree
ExpandAll() CollapseAll()
Node
Collapse(), Expand(), ExpandAll(), Toggle().
160
TreeView
161
NumericUpDown v DomainUpDown
163
NumericUpDown
NumericUpDown control cho php chn mt s (nguyn/thc) trong min gii hn Properties Maximum, Minimum Gi tr ln nht v nh nht c th chn Increment Bc nhy mi ln click DecimalPlaces S ch s l Value Gi tr hin ti ca control Methods void DownButton() void UpButton() Events ValueChanged S kin xy ra khi value thay i
164
DomainUpDown
DomainUpDown cung cp mt danh sch cc option (tng t nh List control), nhng ngi dng ch c th chn cc item thng qua up/down button Properties
Text SelectedIndex SelectedItem Items
Methods
void DownButton() void UpButton()
165
DomainUpDown
166
TrackBar
TrackBar cho php ngi dng chn gi tr s nguyn mt cch ha dng Tab across
Properties
Maximum, Minimum Value TickFrequency SmallChange, LargeChange
Events
ValueChanged Scroll
167
HScrollBar v VScrollBar
Properties
Value: int Maximun: int Minimum: int SmallChange: int LargeChange: int RightToLeft: RightToLeft
Yes No
Events
Scroll, ValueChanged
168
HScrollBar v VScrollBar
Bi tp luyn tp
Vit chng trnh chnh sa mu c giao din nh sau
169
ProgressBar
ProgressBar
171
ProgressBar
Properties
Step Bc nhy mi ln Maximum, Minimum Gi tr ln nht v nh nht Value Gi tr hin ti
Phng thc
void PerformStep() Tng mt lng Step void Increment(int value) Tng mt lng value
172
PictureBox v Bitmap
PictureBox
174
PictureBox
Properties
Image Lu tr hnh ang hin trn PictureBox
*.gif, *.jpg, *.jpeg, *.bmp, *.wmf, *.png, *.tiff
Events
SizeModeChanged
175
PictureBox
Np nh t file
string path = ; Bitmap bitmap = new Bitmap(path); pic.Image = bimap;
pic.SizeMode=PictureBoxSizeMode.StretchImage;
176
Bitmap
Image
Bitmap
Metafile
177
Bitmap
Properties
Width,Height, Size chiu rng, chiu cao nh (pixel)
Methods
void GetPixel(int x, int y) void SetPixel(int x, int y, Color color) void RotateFlip(RotateFlipType rotate); Save(string fileName) Save(string fileName, ImageFormat format)
178
PictureBox v Bitmap
Bi tp luyn tp
Vit chng trnh x l nh c bn, gm nhng chc nng c bn sau
Chn file nh, Lu nh Quay nh Hin th thng tin ca nh Cch hin th nh (SizeMode) Ly mu ti v tr chut trn nh
179
MaskedTextBox v RichTextBox
MaskedTextBox v RichTextBox
MaskedTextBox RichTextBox
181
MaskedTextBox
MaskedTextBox
Properties
Mask: string
Methods
void ResetText() Thit lp default text void Copy(), Cut(), Paste()
183
MaskedTextBox
Mask
0 phi nhp s ([0..9]) 9 s hay space (option) L phi nhp k t ch ([a-zA-Z]) ? k t ch (option) & phi nhp k t ascii C nhp k t ascii (option) A phi nhp Alphanumeric a nhp Alphanumeric (option)
184
MaskedTextBox
Mask
. thp phn , phn cch phn ngn : phn cch thi gian / phn cch ngy $ k hiu tin t < chuyn sang ch thng > chuyn sang ch HOA \ Escape (\\ l \)
185
MaskedTextBox
V d
00/00/0000 ngy (999)-000-0000 s in thoi M $999,999.00 tin t 0 n 999999
186
RichTextBox
Properties Text: string Vn bn trong RichTextBox Rtf: string Code ca vn bn SelectionText, SelectionRtf: string Mt phn vn bn hay code ca vn bn c chn SelectionColor, SelectionBackColor : Color vn bn c chn SelectionFont: Font font ca vn bn c chn
RedoActionName Ly tn action khi phng thc Redo() gi UndoActionName Ly tn action khi phng thc Undo() gi ZoomFactor Mc zoom
187
RichTextBox
Methods void LoadFile(string path) void SaveFile(string path) void Redo() void Undo() void Copy() void Cut() void Paste() void Clear() Xa tt c cc text void SelectAll() Chn tt c cc text int Find(string string str) Events LinkClicked, SelectionChanged
188
RichTextBox
Bi tp luyn tp
Vit chung trnh son tho vn bn c nh dng nh MS.Word
189
191
DateTimePicker v MonthCalender
Chn mt ngy
192
DateTimePicker
DateTimePicker cho php user chn mt ngy Properties
Text, Value: Text tr v chui ngy c nh dng, Value tr v i tng DateTime Format: nh dng hin th
long, short, time, custom
CustomFormat:
dd/mm/yyyy: Ngy/Thng/Nm hh:mm:ss: Gi:Pht:Giy
193
MonthCalender
Properties
SelectionStart, SelectionEnd: tr v cc ngy chn SelectionRange: cu trc cha SelectionStart v SelectionEnd MaxDate, MinDate, MaxSelectionCount: ngy ti a v ti thiu c chn trong calender, v s ngy lin tc c th chn ti mt thi im
194
Timer
Timer sinh ra s kin Tick theo nh k Properties
Interval: int thi gian s kin xy ra (tnh bng millisecond) Enabled: bool Cho php timer start hay stop
Methods
void Start() Start timer void Stop() Stop timer
Events
Tick
195
Menu v Toolbar
197
Menu
Mt menu gm 2 phn: Cc mc menu (Item) v b cha cc mc menu (Container) Container: Lp MenuStrip
Items Cha cc MenuItem/TextBox/ComboBox Visible n hin menu TextDirection Hng v text trn item LayoutStyle Cch hin th menu
Cc mc menu:
Lp ToolStripMenuItem
Text Visible ShortcutKeys ShowShortcutKeys Checked
Lp ToolStripTextBox Lp ToolStripComboBox
198
Menu
T thit k menu
HotKey: thm k t & trc k t mun lm hot key
nh tn cc mc menu
199
Menu
200
Menu
To Shortcut key
Chn mc menu Vo properties thit lp ShortcutKeys
201
Menu
202
Menu
X l s kin:
X l s kin cho tng mc menu item
Click DoubleClick CheckedChanged CheckStateChanged
203
Context menu
Context menu l menu ng cnh xut hin ti cc control khi click phi chut ln control tr gip user hiu v control Container
ContextMenuStrip
Cc bc to Context menu
B1: To ContextMenuStrip B2: Vo Properties ca control mun c menu ng cnh: gn ContextMenuStrip bng contextmenu to B1 B3: X l cc s kin trn cc menu item ca Context menu
204
ToolBar
ToolBar
Cc loi Item
206
ToolBar
Cc bc to toolbar
B1: To container: Ko ToolStrip vo form B2: To cc item
Chn loi item Chn hnh
207
StatusBar
208
NotifyIcon v ToolTip
NotifyIcon v ToolTip
NotifyIcon ToolTip
210
NotifyIcon
NotifyIcon dng to mt icon trn System Tray Properties
BalloonTipIcon: ToolTipIcon BalloonTipText: string BalloonTipTitle: string ContextMenuStrip Icon: Icon Text: string
Methods
void ShowBalloonTip(int timeout) void ShowBalloonTip(int timeout, string title, string text, ToolTipIcon icon)
211
ToolTip
212
ToolTip
Properties
InitialDelay: int AutomaticDelay: int ShowAlways: bool BackColor, ForeColor: Color ToolTipTitle: string ToolTipIcon: ToolTipIcon.(Error, Info, None, Warning)
Events
ToolTip
Cc bc to tooltip
B1: Ko ToolTip vo form v thit lp cc properties B2: Chn control mun c properties B3: Vo properties nhp dng vn bn ti: ToolTip on tntooltip
214
Grouping Controls
Grouping Controls
216
Properties
Enabled: bool Size: Size Visible: bool
Methods
void Focus() void Refresh()
Events
Enter Leave Paint
217
GroupBox
218
Panel
Panel
219
TabControl
Properties
TabPages SelectedTab ShowTooltips , Multiline, TabCount, SelectedIndex
Events
SelectedIndexChanged
220
Cc loi Dialog
Custom Dialog Boxes Common Dialog Boxes
OpenFileDialog SaveFileDialog FontDialog ColorDialog FolderBrowserDialog PageSetUpDialog PrintPreviewDialog PrintDialog
222
Bn bc s dialog
Cu hnh dialog (thit lp cc properties) Hin dialog bng phng thc ShowDialog() Xc nh ngi dng nhn OK hay Apply (a trn kiu tr v DialogResult) Vit code thc hin da trn hnh ng ca user trn dialog
223
224
Properties
DefaultExt: string AddExtension: bool Title: string IntialDirectory: string ShowReadOnly: bool ReadOnlyChecked: bool MultiSelect: bool
Methods
DialogResult ShowDialog() Strean OpenFile()
225
226
Properties
OverwritePrompt: bool
FileName: string FileNames: string[] Filter: string DefaultExt: string AddExtension: bool Title: string IntialDirectory: string
Methods
Stream OpenFile() DialogResult ShowDialog()
227
228
Properties
Font Color MaxSize, MinSize ShowColor: bool ShowApply: bool ShowEffects: bool
Methods
DialogResult ShowDialog() void Reset()
229
230
Properties
Color AllowFullOpen: bool FullOpen: bool
Methods
DialogResult ShowDialog() void Reset()
231
232
Properties
Description: string RootFolder: Environment.SpecialFolder SelectedPath: string ShowNewFolderButton: bool
Methods
DialogResult ShowDialog() void Reset()
233
MDI
To MDI
To Form cha
IsMdiContainer = true
To form con
To object form con: ChildFormName f = new ChildFormName() f.MdiParent = this; f.Show();
235
Tm form cha
this.MdiParent
Tm cc form con
this.MdiChildren
236
ng b d liu
Ch :
Form cha lu cc form con Mi form con lu 1 form cha
237
Sp xp cc form con
Sp xp cc form con
this.LayoutMdi(MdiLayout.ArrangeIcons); Cascade, TileHorizontal, TileVertical
238
c file d liu vn bn
File vn bn
Namespace
System.IO
Class c bn
StreamReader StreamWriter
240
File vn bn
c file vn bn
StreamReader sr = new StreamReader(path); string data = sr.ReadLine(); sr.Close();
241
File vn bn
Ghi file vn bn
StreamWriter sw = new StreamWriter(path); sw.WriteLine(); sw.Close();
242
Mt s Bi tp ln
243