You are on page 1of 61

Lm vic vi Windows form

Trn Duy Hong tdhoang@fit.hcmus.edu.vn

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

M hnh s l s kin
Application Message handlers Retrieved messages Dispatched messages

WM_KEYDOWN WM_MOUSEMOVE

OnKeyDown

OnMouseMove

WM_PAINT
Messages

Message queue

Message loop

OnPaint Window procedure

Cu trc ng dng
ng dng Windows form c 3 phn chnh
Application Cc Forms trong Application Cc Controls v Components trn Form

Lp Application
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)

Lp 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

Lp 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

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

Lp Form
System.Windows.Forms Hnh thnh giao din s dng Sp xp v thit k cc control c bn

Lp Form
Nhm thuc tnh hin th
BackColor
this.BackColor = Color.White;

ForeColor
this.ForeColor = Color.Black;

BackgroundImage
this.BackgroundImage = new Bitmap("background.jpg");

Text
this.Text = Quan ly Hoc sinh;

FormBorderStyle
this.FormBorderStyle = FormBorderStyle.None;

Lp Form
Nhm thuc tnh layout
Size
this.Size = new Size(100,100);

ClientSize
this.ClientSize = new Size(100,100);

StartPosition
this.StartPosition = FormStartPosition.CenterScreen;

WindowState
this.WindowState = FormWindowState.Maximized;

Lp Form
Nhm thuc tnh misc
AcceptButton
this.AcceptButton = btnDangNhap;

CancelButton
this.CancelButton = btnBoQua;

Lp Form
Nhm thuc tnh window style
IsMdContainer
this.IsMdContainer = true;

Opacity
this.Opacity = 0.5;

ControlBox MaximizeBox / MinimizeBox Icon


this.Icon = new Icon(icon.ico);

Lp Form
V d : trong hm form_load
private void DemoForm_Load(object sender, EventArgs e) { this.Text = "Demo"; this.Size = new Size(500, 500); this.BackgroundImage = new Bitmap("background.jpg"); this.Opacity = 0.75; }

Lp Form

Lp Form
Thuc tnh Controls
Cha danh sch cc control con ca n Thm xa ng cc control vo form
Button btn = new Button; btn.Text = Hello; btn.Size = new Size (50, 50); btn.Location = new Point (10,10);

this.Controls.Add(btn);

Lp Form
V d : thm 1 mng button
this.ClientSize = new Size(500, 500); Button[,] arrButton = new Button[10, 10]; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { arrButton[i,j] = new Button(); arrButton[i,j].Size = new Size(50, 50); arrButton[i,j].Location = new Point(j * 50, i * 50); this.Controls.Add(arrButton[i,j]); } }

Lp Form

Lp Form
Danh sch cc hm
Show()
this.IsMdContainer = true; FrmThemHocSinh frm = new FrmThemHocSinh(); frm.Show();

ShowDialog()
FrmThemHocSinh frm = new FrmThemHocSinh(); frm.ShowDialog(); if (frm.DialogResult == DiaLogResult.OK) { MessageBox.Show(Them thanh cong); }

Lp Form
Cc s kin ng m form
Load() Closing()
DialogResult r = MessageBox.Show(Ban co muon thoat, Thong bao, MessageBoxButtons.YesNo) if (r == DialogResult.No) e.Cancel = true;

Closed()

Lp Form
Cc s kin v bn phm
Thuc tnh KeyPreview
this.KeyPreview = true;

KeyPress()
if (char.IsLower(e.KeyChar)) e.KeyChar = char.ToUpper(e.KeyChar); if (!char.IsDigit(e.KeyChar)) e.Handled = true;

Lp Form
Cc s kin v bn phm
KeyDown(), KeyUp()
if (e.KeyCode == Keys.F5) { ThemNhanVien(); e.Handled = true; } if (e.KeyCode == Keys.N && e.Control == true) { ThemNhanVien(); e.Handled = true; }

Lp Form
Cc s kin v chut
MouseDown() MouseUp() MouseEnter() MouseHover() MouseLeave()

MessageBox
Message Box hin mt thng bo hay mt hng dn cho user Lp MessageBox ch cha mt phng thc tnh duy nht: Show()

MessageBox
DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options);

MessageBox
public enum MessageBoxButtons { OK, public enum MessageBoxIcon OKCancel, { AbortRetryIgnore, Asterisk = 0x40, YesNoCancel, Error = 0x10, public enum DialogResult YesNo, Exclamation = 0x30, { RetryCancel Hand = 0x10, None, } Information = 0x40, OK, None = 0, Cancel, Question = 0x20, Abort, Stop = 0x10, Retry, Warning = 0x30 Ignore, } Yes, No }

MessageBox
DialogResult result = MessageBox.Show("Ban co muon thoat?", "Demo", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { this.Close(); }

Cc control thng dng


Textbox Button CheckBox RadioButton ComboBox ListView TreeView

TextBox
Cc thuc tnh
CharacterCasing
txtHoTen.CharacterCasing = CharacterCasing.Upper;

Multiline
txtDiaChi.Multiline = true;

PasswordChar
txtMatKhau.PasswordChar = '*';

MaxLength
txtHoTen.MaxLength = 20;

TextBox
Cc thuc tnh
Text SelectedText SelectionStart SelectionLength

TextBox
Cc s kin
Validating() / Validated() TextChange

TextBox
Auto complete
AutoCompleteMode
Append Suggest SuggestAppend

AutoCompleteSource
FileSystem / FileSystemDirectories AllUrl / HistoryList CustomSource

AutoCompleteCustomSource

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 event thng dng


Click, MouseEnter, MouseLeave

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;

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

RadioButton
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

RadioButton
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

ComboBox
Cc thuc tnh
Items Sorted = true Text, SelectedIndex, SelectedItem

S kin
SelectedIndexChange

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

ListView
Th hin dng li hoc icon ca cc items con. Thuc tnh
Columns Items View (LargeIcon, SmallIcon, Detail, List) FullRowSelect SmallImageList / LargeImageList

S kin ItemActivate

ListView
Mi item trong ListView l 1 ListViewItem Thuc tnh ListViewItem
Text SubItems (Ch dng khi View ca ListView l Detail) ImageIndex

ListView
// them cot vao listview lvwDir.Columns.Add("Name", 200, HorizontalAlignment.Left); lvwDir.Columns.Add("Size", 80, HorizontalAlignment.Right); lvwDir.Columns.Add("Type", 80, HorizontalAlignment.Left); lvwDir.Columns.Add("Date Modified", 160, HorizontalAlignment.Left);
// hien thi theo dang chi tiet lvwDir.View = View.Details;

ListView
// them danh sach hinh cho icon cua listview lvwDir.SmallImageList = new ImageList(); lvwDir.SmallImageList.Images.Add(new Icon("icons/folder.ico")); lvwDir.SmallImageList.Images.Add(new Icon("icons/document.ico"));

ListView
foreach (DirectoryInfo subDir in curDir.GetDirectories()) { ListViewItem lvi = new ListViewItem(); lvi.Text = subDir.Name; lvi.SubItems.Add(""); lvi.SubItems.Add("Folder"); lvi.SubItems.Add(subDir.LastWriteTime.ToString()); lvi.ImageIndex = 0; lvi.Tag = subDir; lvwDir.Items.Add(lvi) }

TreeView
Th hin dng Cy Tng node bn trong n l 1 TreeNode Trong 1 TreeNode c th c 1 hoc nhiu TreeNode con

TreeView
Thuc tnh TreeView
Nodes SelectedNode ImageList

S kin TreeView
AfterSelect BeforeSelect

Phng thc TreeView


CollapseAll ExpandAll

TreeView
// them danh sach cac icon tvwDir.ImageList = new ImageList(); tvwDir.ImageList.Images.Add(new Icon("icons/mycomputer.ico")); tvwDir.ImageList.Images.Add(new Icon("icons/drive.ico")); tvwDir.ImageList.Images.Add(new Icon("icons/folder.ico")); tvwDir.ImageList.Images.Add(new Icon("icons/document.ico"));

TreeView
// them nut My computer va cac o dia TreeNode myComputerNode = new TreeNode("My computer"); myComputerNode.Tag = "My computer"; myComputerNode.ImageIndex = 0; tvwDir.Nodes.Add(myComputerNode);

TreeView
// them cac node o dia vao mycomputer node foreach (DriveInfo drive in DriveInfo.GetDrives()) { TreeNode driveNode = new TreeNode(drive.Name); driveNode.Tag = drive.RootDirectory; driveNode.ImageIndex = 1; myComputerNode.Nodes.Add(driveNode); }

Thuc tnh, hm chung


TabIndex TabStop Enable
btnSave.Enable = false; ThemNhanVien(); btnSave.Enable = true;

Focus()
If (txtHoTen.Text == ) { MessageBox.Show (Ban chua nhap ho ten); txtHoTen.Focus(); }

Dialog thng dng


OpenFileDialog
OpenFileDialog dialog = new OpenFileDialog(); dialog.InitialDirectory = Application.ExecutablePath; dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; dialog.FilterIndex = 2; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { MessageBox.Show(dialog.FileName); }

Dialog thng dng


SaveFileDialog
SaveFileDialog dialog = new SaveFileDialog(); dialog.InitialDirectory = Application.ExecutablePath; dialog.Filter = "txt files (*.txt)|*.txt"; dialog.RestoreDirectory = true; if (dialog.ShowDialog() == DialogResult.OK) { MessageBox.Show(dialog.FileName); }

Dialog thng dng


FolderBrowserDialog
FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.RootFolder = Environment.SpecialFolder.Desktop; dialog.ShowNewFolderButton = true; if (dialog.ShowDialog() == DialogResult.OK) { MessageBox.Show(dialog.SelectedPath); }

Dialog thng dng


FolderBrowserDialog

Dialog thng dng


ColorDialog FontDialog

Timer
Thuc tnh
Interval : chu k ca timer (mili giy)

S kin
Tick

Phng thc :
Start : bt u timer Stop : dng timer

SendKeys
Gi 1 thao tc phm n ng dng V d :
SendKeys.Send(A); SendKeys.Send(abc); SendKeys.Send({Enter}); SendKeys.Send(A{Enter}); SendKeys.Send(+(abc)); // shift SendKeys.Send(^(abc)); // ctrl SendKeys.Send(%(abc)); // alt

Thit k layout
S dng Toolbar LayOut Thit k v tr cc control trong giao din nh:
Thc hin sp xp Canh chnh kch thc gia cc control Canh ta cho nhiu control

Chn ToolBar LayOut

Thit k layout
Toolbar c enable

Chn 2 control tr ln

Thit k layout
Cch thao tc:
Bc 1: Chn ti thiu 2 controls (Nhn phm Ctrl + click chut tri ln cc control c chn) Bc 2: Chn cc biu tng trong thanh Layout ToolBar

Dock, Anchor
Khi c s thay i kch thc hoc v tr ca control cha th control con trong n s m bo c kch thc v v tr tng ng thng qua thuc tnh Dock v Anchor. Bt k control no trong .NET u c 2 thuc tnh Dock v Anchor
Dock: Xc nh kch thc ca control so vi control (cha) ang cha n. Anchor: Xc nh v tr ca control so vi control (cha) ang cha n

You might also like