You are on page 1of 243

Chng 3

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

Lp trnh C# trn Windows

Lp trnh trn Windows Khi nim

Message (Thng ip)


Mt message l mt con s nguyn c quy c trc gia Windows v cc ng dng (Application) Cc d liu nhp (t bn phm, t chut, ) u c Windows chuyn thnh cc message v mt s thng tin km theo message V d
0x0001 0x0002 0x0003 0x0005 0x0012 WM_CREATE WM_DESTROY WM_MOVE WM_SIZE WM_QUIT

Lp trnh trn Windows Khi nim

System Queue (Hng i h thng):


Windows cha cc message trong mt hng i gi l hng i h thng.

Application Queue (Hng i ng dng ):


Cc ng dng c hng i ring cha cc message ca ng dng gi l hng i ng dng.

Windows s t ng phn b cc message


t System Queue n cc Application Queue

Lp trnh trn Windows Khi nim


H iu hnh Windows Hardware input

Hng i h thng

ng dng A Hng i ca ng dng A

Message loop

Nhn v x l

Hng i ca ng dng B Message loop Nhn v x l

ng dng B

Lp trnh trn Windows Event-driven programming model

Message loop (vng lp thng ip)


Mi Application ti mt thi im c mt message loop ly cc message trong Application Queue v phn b cho cc ca s (Window) trong Application

Hm Window Procedure
Mi ca s (Window) trong Application u c mt hm Window procedure x l cc message do message loop nhn v

Lp trnh trn Windows Event-driven programming model


Application Message handlers

Dispatched messages

Retrieved messages

WM_KEYDOWN

OnKeyDown

WM_MOUSEMOVE
WM_PAINT Messages Message queue

OnMouseMove

Message loop

OnPaint

Window procedure

10

Lp trnh trn Windows Event-driven programming model

Event-driven programming model:


ng dng phn ng cc s kin (nhn phm, click chut, ...) bng cch x l cc message do Windows gi n Mt ng dng Windows in hnh thc hin mt lng ln cc x l phn hi cc message n nhn. V gia cc message n ch message k tip n

Message queue: Cc message c ch trong message queue cho n khi chng c nhn x l

11

Lp trnh trn Windows Event-driven programming model



Hm Main: Hm Main to mt ca s v vo message loop Message loop: Nhn cc message v phn b chng n Window Procedure ca cc ca s Message loop kt thc khi nhn c WM_QUIT (chn Exit t menu File, click ln close button) Window Procedure: Phn ln cc on m t trong Window Procedure. Window Procedure x l cc message gi n ca s Window Procedure in hnh cha cu lnh switch ln vi mi case l mt message ring. Message handler: Code cung cp x l message c th gi l message handler

12

Lp trnh trn Windows Event-driven programming model

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

Lp trnh trn Windows Event-driven programming model


Application Message handlers gi cc s kin tung ng

Dispatched messages

Retrieved messages

WM_KEYDOWN

OnKeyDown

WM_MOUSEMOVE
WM_PAINT Messages Message queue

OnMouseMove

Application.Run()

OnPaint

WndProc(ref Message m)

14

To ng dng Windows Forms t u

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

Cch 1: Trc tip tha k


Thit k giao din
To lp tha tha k t lp Form B cc cc control Thit lp cc property cho cc control

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

Cch 2: Gin tip qua cc field event


Thit k giao din
B cc cc control Thit lp cc property cho cc control

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]

Bc 2: using cc namespace using System.Windows.Forms; using System.Drawing; Bc 3: Thm class file


Click phi ln project Add Class...

Bc 4: Vit code Bc 5: menu Project Property Output type: Windows Application

19

Dng Form, Khng tha k

class Program { static void Main() { Form form = new Form(); form.Text = First Application; Application.Run(form); }

20

Dng Form, Khng tha k

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

Dng Form, Khng tha k

Event Handler
class Program { static void Main() { Form form = new Form(); form.Text = WinForm; form.Click += form_Click; Application.Run(form); }

static void form_Click(object sender, EventArgs e) { MessageBox.Show("Ban da click vao form"); }


}
22

Dng Form, Khng tha k

Thm control vo form


class Program { static void Main() { Form form = new Form(); form.Text = "WinForm"; Button button = new Button(); button.Text = "OK"; button.Location = new Point(100, 100); button.Click += new EventHandler(button_Click); form.Controls.Add(button); Application.Run(form); } static void button_Click(object sender, EventArgs e) { MessageBox.Show("Ban da click vao nut OK"); } }
23

Dng form bng cch k tha


class MainForm:Form { public MainForm() { this.Text = "WinForm"; button = new Button(); button.Text = "OK"; button.Location = new Point(100, 100); button.Click += new EventHandler(button_Click); this.Controls.Add(button); }

void button_Click(object sender, EventArgs e) { MessageBox.Show("Ban da click vao nut OK"); }


private Button button; }
24

Dng form bng cch k tha


class Program { static void Main() { MainForm form = new MainForm(); Application.Run(form); } }

25

Dng form bng cch k tha

Bt cc s kin trn form


Cch 1: Thng qua field event
class MainForm:Form { public MainForm() { this.Text = "WinForm"; this.Click += form_Click; } void form_Click(object sender, EventArgs e) { MessageBox.Show("Ban da click vao form"); } }
26

Dng form bng cch k tha

Bt cc s kin trn form


Cch 2: Thng Qua override cc message handler
class MainForm:Form { public MainForm() { this.Text = "WinForm"; } protected override void OnClick(EventArgs e) { base.OnClick(e); MessageBox.Show("Ban da click vao form"); } }
27

To ng dng Windows Forms t Wizard

To ng dng bng Wizard

Bc 1: To Empty Project
File New Project Project Type: Visual C# Windows Template: Windows Forms Application

29

To ng dng bng Wizard

Cc thnh phn ca ca s thit k

Solution Windows

Form ang thit k

Properties Windows

Toolbox
30

To ng dng bng Wizard

Bc 2: Thit k giao din: Ko cc i tng t Toolbox vo form

31

To ng dng bng Wizard

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

Gii thch ngha ca mc ang chn


32

To ng dng bng Wizard

Bc 4: Bt cc s kin cho cc i tng trn form t Properties Windows

33

To ng dng bng Wizard

Bc 5: X l nghip v bng cc vit code cho


cc event handler

34

Code do Wizard sinh ra

Lp Program

35

Code do Wizard sinh ra

Lp MainForm

36

Code do Wizard sinh ra

Phng thc InititiallizeComponent()

37

Tng quan cc i tng trong Windows Forms

Cu trc ca ng dng

ng dng Windows Forms c 3 phn chnh


Application Cc Form trong Application Cc Controls v Components trn Form

39

Lp Application

Application Khi nim

Lp Application cung cp cc phng thc tnh v cc property tnh qun l ng dng


Cc phng thc start, stop ng dng, x l Windows messages, Cc property ly thng tin v ng dng Lp ny khng th tha k

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

Mt s phng thc thng dng


Run(Form) bt u message loop ca ng dng Exit() dng message loop DoEvents() x l cc message trong khi chng trnh ang trong vng lp EnableVisualStyles() cc control s v vi kiu visual nu control v h iu hnh h tr Restart() dng ng dng v T ng restart li

45

Application

Mt s property thng dng


ExecutablePath ng dn n file .exe StartupPath ng dn n th mc cha file .exe UseWaitCursor Hin cursor dng Wait

Event thng dng


Idle Xut hin khi ng dng hon thnh vic x l

46

Application

V d

class Program { static void Main() { Application.Run(new MainForm); } }

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

.NET Component Khi nim

Component l mt thnh phn phn mm Lp Component l lp c s ca tt c cc


component

Namespace:
System.ComponentModel

Assembly
System (System.dll)

50

.NET Component Khi nim

Cc component trong .NET gm c cc thnh vin:


Properties Methods Events [Cc thnh vin protected]

Cc Component khng h tr tng tc vi ngi dng bng form giao din t nhin

Nonvisual design surface


51

.NET Component S tha k


System.Object System.MarshalByRefObject System.ComponentModel.Component
System.Data.Common.DbConnection System.Diagnostics.PerformanceCounter System.Diagnostics.Process System.Timers.Timer System.Windows.Forms.Control System.Windows.Forms.ErrorProvider System.Windows.Forms.HelpProvider System.Windows.Forms.ImageList System.Windows.Forms.Menu System.Windows.Forms.NotifyIcon System.Windows.Forms.StatusBarPanel System.Windows.Forms.Timer System.Windows.Forms.ToolBarButton System.Windows.Forms.ToolStripItem System.Windows.Forms.ToolStripPanelRow System.Windows.Forms.ToolTip
52

.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

Control Khi nim

Control l Component c giao din


Giao din ng dng gm mt tp cc control, gip ngi dng tng tc vi ng dng Cho php hin th d liu (output) hay cho php nhp d liu vo (input)

Lp Control l lp c s cho cc control

Namespace
System.Windows.Forms

Assembly
System.Windows.Forms (System.Windows.Forms.dll)

55

Control Khi nim

Cc control thng dng


Label Textbox Button Radio button Checkbox ListBox ComboBox Scrollbar

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

event event event event

KeyEventHandler KeyDown; KeyPressEventHandler KeyPress; KeyEventHandler KeyUp; PreviewKeyDownEventHandler PreviewKeyDown;

// 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;

// Private public event EventHandler HandleCreated; public event EventHandler HandleDestroyed; }

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 Khi nim

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

Mt s phng thc thng dng


Show(), ShowDialog(), Hide(), Close() CenterToScreen(), DrawToBitmap(), Invalidate() CreateGraphic();

Mt s property thng dng khc (khng c trong Design)


MdiParent, MdiChilden DialogResult class MyForm : Form Controls { public MyForm() Modal
{ this.ShowInTaskbar = false; this.Location = new Point(10, 10); this.Size = new Size(100, 100); } }
80

Lp Form Chu trnh i sng ca form

Move Load VisibleChanged Activated Shown Paint Deactivate Closing Closed


81

Lp Form Mt s vn lin qua n Form

To custom form
Click phi ln project trong solution Chn Add Windows Forms Cho custom form tha k t lp Form

Hin custom form


Modal Form
formName.ShowDialog();

Modeless Form
formName.Show ();
82

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

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

Lp Form Mt s vn lin qua n Form

Thit lp gi cc tr ty theo Form l Modal


Form hay Modeless Form
Ty thuc vic dng Show() hay ShowDialog(), property Modal s c gi tr true hay false Cch cc form c hin th khng c bit khi form c to, cho nn gi tr Modal khng th xc nh trong constructor m phi xc nh trong s kin load hay cc s kin sau .
91

Lp Form Mt s vn lin qua n Form


private void Form_Load(object sender, EventArgs e) { if (this.Modal) { // Khi to gi tr khi l form Modal this.FormBorderStyle = FormBorderStyle.FixedDialog; } else { // Khi to gi tr khi l form Modeless this.FormBorderStyle = FormBorderStyle.Sizable; } }

92

Lp Form Mt s vn lin qua n Form

Trao i d liu gia cc Form


Vi Modal Form

93

Lp Form Mt s vn lin qua n Form

Trao i d liu gia cc Form


Vi Modeless Form

94

Lp Form Mt s vn lin qua n Form

Kim tra c mun ng Form hay khng


X l s kin Closing Nu khng mun ng form: e.Cancel = true

Th t active ca cc control trn form


(TabIndex)
View Tab Order

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

B cc cc controls trn Form

B cc cc controls trn form

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

Dock: Ch ra cc cnh ca control s bm vo container


Left, Top, Right, Bottom, Fill

98

B cc cc controls trn form

Lp Splitter: Mt splitter control cho php


thay i kch thc ca cc control dock

Th t active ca cc control trn form


(TabIndex)
View Tab Order

99

Cc control thng dng

Cc control thng dng

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

TextBox control dng nhp chui vo ng dng


Cho php nhp nhiu dng To mt n nhp password

Mt s property thng dng


Text, CharacterCasting, ReadOnly, PasswordChar (Multiline=false), MaxLength Multiline, ScrollBars, WordWrap, Lines[], AcceptTab, AcceptReturn

Mt s phng thc thng dng


Clear(), Cut(), Paste(), Copy(), Undo(), Select(), SelectAll(), DeselectAll(), ProcessCmdKey()

Mt s event thng dng


Click, Enter, Leave,TextChanged, MultilineChanged, KeyPress

104

TextBox

Auto Completion Text


Controls: TextBox v ComboBox

AutoCompleteSource
RecentlyUsedList HistoryList AllUrl = RecentlyUsedList + HistoryList ListItems

AutoCompleteMode
Append Suggest SuggestAppend

105

TextBox

Auto Completion Text


Custom Source
AutoCompleteCustomSource: danh sch data AutoCompleteSource: CustomSource

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

LinkLabel control: L mt label cho php


cha cc hyperlink

Mt s property thng dng


LinkBehaviour , LinkVisited VisitedLinkColor, LinkColor, ActiveLinkColor, DisabledLinkColor LinkArea (mt lin kt), Links (nhiu lin kt)

Mt s event thng dng


LinkClicked

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

Button control: cho php user click ln n thc hin mt hnh ng

Mt s property thng dng


Text, Image, TextAlign, ImageAlign, DialogResult

Mt s phng thc thng dng


PerformClick()

Mt s event thng dng


Click, MouseEnter, MouseLeave

111

Button

Cc cch chn Button control


Dng mouse click button Gi s kin Click ca button Focus button (tab) sau nhn SPACEBAR hay ENTER Nhn Access Key (ALT + K t gch di) Nu button l access button ca form nhn ENTER Nu button l Cancel button ca form nhn ESC Gi phng thc PerformClick()

112

Button

Access Key cho control


Access Key l k t gch di trong text ca menu, menuitem, label ca cc controls nh button User c th click vo control bng cch nhn ALT + Access key

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

Hai phng thc vo mt s kin To Button ng


Cho nhp thng tin (vi tr, text, ) ri hin button trn form

Popup Text cho button (HelpProvider)

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

Cc dng khc ca CheckBox


ThreeState = true: CheckBox c 3 trng thi Appearance =Button: CheckBox l mt button

CheckBox 3 trng thi


Dng property CheckState kim tra n c l mt trong 3 trng thi
Checked Unchecked Indeterminate

118

Radio Buttons

Radio buttons tng t checkbox, tuy nhin


Cc button trong cng nhm ch c mt button c check ti mt thi im Mt nhm: Cc radio button c t trong cng container thng l panel hay group box

119

Radio Buttons

Property Checked Cho bit button c c


check hay khng

Event CheckedChanged S kin pht sinh


khi check box c check hay khng c check

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

Thm item vo item list listName.Items.Add(); listName.Items.AddRange(String []);

Chn item vo item list listName.Items.Insert(index, data);


Xa: listName.Items.Remove(data); listName.Items.RemoveAt(index); listName.Items.Clear(); Tm kim listName.Items.Indexof(object obj);

124

ListBox

ListBox control cho php hin th danh sch cc mc user chn

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

CheckedListBox control Hin danh sch cc checkbox

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

C th kt ni control vi d liu thng qua


property DataSource vi
DataSet, Mng (tnh v ng)

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

Thm/xa/sp xp cc nh trong ImageList


Cch 1: Dng Designer thm cc nh (bmp, jpg, ico, ) vo
Click () k bn thuc tnh Image trong Properties

135

ImageList

Thm/xa/sp xp cc nh trong ImageList


Ch : cc file nh c thm vo resource file khi dng designer Cch 2: Np cc file nh t file vo 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

Listview l control dng trnh by danh


sch cc mc m c th trnh by bng 1 trong 4 cch khc nhau
Cc item trong ListView l mt i tng ListViewItem

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

Nhn d liu trn ListView


ListViewItem item = lstSignature.SelectedItems[0]; string sub1 = item.SubItems[0].Text; string sub2 = item.SubItems[1].Text;

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

Ch : Details phi c column

148

ListView

Mt s properties khc
AllowColumnReorder AutoArrange CheckBoxes, CheckedIndices, CheckedItems GridLines

Mt s methods khc
BeginUpdate(), EndUpdate()

149

TreeView

TreeView l mt collection cc node dng


phn cp

Cc node trong cy thuc lp TreeNode, c


th c lng khng gii hn.

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

V d 1 TreeNode node; node = tree.Nodes.Add(cha); node.Nodes.Add(con);

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

Duyt cc phn t ca TreeView: 2 k thut


c bn
Dng k thut quy
void XuLyCacNode(TreeNodeCollection nodes) { foreach (TreeNode node in nodes) { // X l node XuLyCacNode (node.Nodes) } }

155

TreeView

Duyt cc phn t ca TreeView: 2 k thut


c bn
Dng cc properties ca node
Parent FirstNode LastNode PrevNode NextNode

156

TreeView

Duyt cc phn t ca TreeView: 2 k thut c bn

Dng cc properties ca node


void XuLyCacNode(TreeNode node) { do { // X l node if (node.Nodes.Count>0) XuLyCacNode(node.FirstNode); node = node.NextNode; } while (node != null); }

157

TreeView

Thao tc trn treeview


Xa node: Remove()
Tham chiu n node cn xa: Xa node Tm v tr node: xa node ti v tr

Xa cc node: Clear() Tm kim v tr: IndexOf()

158

TreeView

Node nh
nh cho ton TreeView
tree.ImageList = imageList; tree.ImageIndex = v tr

nh cho tng node


tree.ImageList = imageList; node.ImageIndex = v tr node.SelectedImageIndex = v tr

159

TreeView

Expand v collaps
Tree
ExpandAll() CollapseAll()

Node
Collapse(), Expand(), ExpandAll(), Toggle().

160

TreeView

Mt s properties khc ca TreeView


CheckBoxes = bool FullRowSelect = bool Indent = number ShowLines, ShowPlusMinus, v ShowRootLines Sorted = bool

Mt s properties khc ca TreeNode


Checked = bool IsSelected = bool IsExpanded = bool

161

NumericUpDown, DomainUpDown, TrackBar v HScrollBar, VScrollBar

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

Thm chui vo DomainUpDown


// Add Items udCity.Items.Add("Tokyo"); udCity.Items.Add("Montreal"); udCity.Items.Add("New York");

Chn item u tin


udCity.SelectedIndex = 0;

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

ProgressBar cho php hin th tin trnh hot ng ca chng trnh

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

SizeMode Kiu enum PictureBoxSizeMode


AutoSize CenterImage Normal StretchSize Zoom

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

Bitmap bao bc GDI+ bitmap: gm d liu pixel v cc thuc tnh ca 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 l m rng ca TextBox


control bng cch dng mt mt n (Mask) hng dn nhp d liu ng n
Yu cu phi nhp hay Option Kiu d liu mong i ti v tr c th

Ch : MaskedTextBox khng h tr Multiline


v Undo
182

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

DateTimePicker, MonthCalender v Timer

DateTimePicker, MonthCalender v Timer

DateTimePicker MonthCalender Timer

191

DateTimePicker v MonthCalender

Chn mt ngy

Chn mt vng 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

MinDate, MaxDate : Ch ra vng ngy user c th chn

193

MonthCalender

MonthCalender cho php user chn mt s ngy trong thng

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, Toolbar v Statusbar

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

Thm menu chun


Click vo k hiu tm gic Insert Standard Items

200

Menu

To Shortcut key
Chn mc menu Vo properties thit lp ShortcutKeys

201

Menu

Cc loi menu item


MenuItem ComboBox TextBox Separator

Ch : Click mi tn xung ti ni mun to


menu item chn cc loi menu item

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 cha tp cc nt c nhng chc


nng khc nhau

Container: Lp ToolStrip Cc item: Lp


ToolStripSplitButton ToolStripDropDownbutton ToolStripLabel ToolStripProgressBar ToolStripSeparator ToolStripComboBox ToolStripTextBox
205

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

B3: X l cc s kin cho cc item

207

StatusBar

Container: StatusStrip Cc loi item

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

ToolTip mt cng c tr gip user hiu r cc


control trn form. ToolTip s hin th mt text khi user r chut vo control

212

ToolTip

Properties
InitialDelay: int AutomaticDelay: int ShowAlways: bool BackColor, ForeColor: Color ToolTipTitle: string ToolTipIcon: ToolTipIcon.(Error, Info, None, Warning)

Events

GetToolTip, SetToolTip, RemoveAll


213

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

Cc loi Grouping Controls


Form Panel GroupBox Tab Control

216

Form, Panel, GroupBox

Properties
Enabled: bool Size: Size Visible: bool

Methods
void Focus() void Refresh()

Events
Enter Leave Paint

217

GroupBox

Hin border xung quanh nhm cc control

Property Text gn Text label cho GroupBox


Control c th c thm vo
t control vo trong GroupBox khi thit k Vit code

218

Panel

Panel ging GroupBox nhng khng c text label

Panel

cha mt cc control nh GroupBox

BorderStyle get/set border style nh


BorderStyle.Fixed3D BorderStyle.FixedSingle BorderStyle.None

219

TabControl

Properties
TabPages SelectedTab ShowTooltips , Multiline, TabCount, SelectedIndex

Events
SelectedIndexChanged

220

Cc dialog thng dng

Cc dialog thng dng

Cc loi Dialog
Custom Dialog Boxes Common Dialog Boxes
OpenFileDialog SaveFileDialog FontDialog ColorDialog FolderBrowserDialog PageSetUpDialog PrintPreviewDialog PrintDialog

222

Cc dialog thng dng

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

Cc dialog thng dng: OpenFileDialog

OpenFileDialog dng chn mt file m ra x l

Properties FileName: string FileNames: string[] Filter: string

224

Cc dialog thng dng: OpenFileDialog

Properties
DefaultExt: string AddExtension: bool Title: string IntialDirectory: string ShowReadOnly: bool ReadOnlyChecked: bool MultiSelect: bool

Methods
DialogResult ShowDialog() Strean OpenFile()

225

Cc dialog thng dng: SaveFileDialog

SaveFileDialog dng chn/nhp mt file


lu ni dung ln a

226

Cc dialog thng dng: SaveFileDialog

Properties
OverwritePrompt: bool
FileName: string FileNames: string[] Filter: string DefaultExt: string AddExtension: bool Title: string IntialDirectory: string

Methods
Stream OpenFile() DialogResult ShowDialog()

227

Cc dialog thng dng: FontDialog

FontDialog dng chn font ch c trn


my

228

Cc dialog thng dng: FontDialog

Properties
Font Color MaxSize, MinSize ShowColor: bool ShowApply: bool ShowEffects: bool

Methods
DialogResult ShowDialog() void Reset()

229

Cc dialog thng dng: ColorDialog

ColorDialog dng chn mu c trn my

230

Cc dialog thng dng: ColorDialog

Properties
Color AllowFullOpen: bool FullOpen: bool

Methods
DialogResult ShowDialog() void Reset()

231

Cc dialog thng dng: FolderBrowserDialog

FolderBrowserDialog dng chn th mc


c trn my

232

Cc dialog thng dng: FolderBrowserDialog

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 cc form trong MDI

Tm form con ang active


this.ActiveMdiChild

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

ng b d liu gia cc form con


B1: Con gi message nh form cha ng b d liu B2: Form cha duyt cc form con ng b d liu

237

Sp xp cc form con

To menu item cha danh sch form con


To menu item Thit lp MdiWindowListItem ca menu container = menu item trn

Sp xp cc form con
this.LayoutMdi(MdiLayout.ArrangeIcons); Cascade, TileHorizontal, TileVertical

Minimize cc form con


Duyt cc form con: this.MdiChildren Thit lp thuc tnh: WindowState = FormWindowState.Minimized

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();

Mt s lnh hay dng


sr.EndOfStream string data = sr.ReadToEnd(); int data = sr.Peek();

241

File vn bn

Ghi file vn bn
StreamWriter sw = new StreamWriter(path); sw.WriteLine(); sw.Close();

Mt s lnh hay dng


sw.Write();

242

Mt s Bi tp ln

Bi tp luyn tp: M phng cc chng trnh sau


NotePad, WordPad Calculator Address Book Duyt file Duyt web Paint Chng trnh xem nh T in Anh Vit Game Minesweeper

243

You might also like