96
Lập trình GUI Khoa Công Nghệ Phần mềm SE.UIT.EDU.VN

3_Lap Trinh GUI

  • Upload
    thit

  • View
    40

  • Download
    7

Embed Size (px)

Citation preview

Page 1: 3_Lap Trinh GUI

Lập trình GUI

Khoa Công Nghệ Phần mềm

SE.UIT.EDU.VN

Page 2: 3_Lap Trinh GUI

Mục tiêu của chương 3

– Mô tả các đặc tính của Window Form

– Tạo window Form

– Kiểm tra dữ liệu trong window form

– Cách tạo Menu

– Các Dialog

– Các control cơ bản trong window form

Page 3: 3_Lap Trinh GUI

1.FORM

Page 4: 3_Lap Trinh GUI

Giao diện người dùng cung cấp phương tiện để người dùng có thể tương tác được với chương trình ứng dụng.

Có hai loại giao diện người dùng:

• Giao diện người dùng dạng ký tự (Character User Interface CUI): người dùng tương tác với chương trình theo câu lệnh nhập từ bàn phím: ví dụ Ms Dos.

• Giao diện người dùng dạng đồ họa (Graphical User Interface GUI): người dùng tương tác với chương trình thông qua hệ thống các window.

Giao diện người dùng đồ họa được hiện thực thông qua Window Form và các control chứa bên trong của nó.

Giới thiệu Window Form

Page 5: 3_Lap Trinh GUI

Các window form dùng để hiển thị tất cả các cửa sổ trong chương trình ứng dụng

Nhận dữ liệu vào từ người dùng và hiển thị thông tin kết quả.

Khi tạo ra 1 project kiểu Window Application, sẽ có 1 window form tự động được thêm vào project.

Tất cả các Window form được thừa kế từ lớp Form chứa trong namespace: System.Windows.Forms

Cũng có thể kế thừa từ các window form có sẵn, rồi thêm vào các tính năng mới.

Giới thiệu về window form

Page 6: 3_Lap Trinh GUI

Visual Studio .Net

controls

designer

Properties,events

Page 7: 3_Lap Trinh GUI

Components API• Properties (Thuộc tính)

• Like member fields• Get, set • Ví dụ Button1.Text = “Press Me”

• Methods (Phương thức)• Like member functions• Tell component to do something• Ví dụ Button1.Show( )

• Events (Sự kiện)• Like callback functions• Receive notifications from component• Ví dụ Button1.Click(e)

Page 8: 3_Lap Trinh GUI

C# WinAppnamespace MyWindowsApplication1 {

public class MyForm1 : System.Windows.Forms.Form {// inherit from Form base class

public MyForm1( ) // constructor, calls InitializeComponent( )

private void InitializeComponent( ) // VS auto-generated GUI code

protected override void Dispose( bool disposing )// standard method to clean up resources

static void Main( ) { // App starts here!Application.Run(new MyForm1( ));

// create a new MyForm1 and run the main event loop }

Page 9: 3_Lap Trinh GUI

Thêm GUI Controlspublic class MyForm1 : System.Windows.Forms.Form {

private System.Windows.Forms.Button button1; … // member variables for each GUI control

private void InitializeComponent( ) // VS auto-generated GUI code

// create GUI controls:this.button1 = new System.Windows.Forms.Button( );

// set properties of GUI controls:this.button1.Text = "button1";

// add controls to their parent or Form:this.Controls.AddRange(

new System.Windows.Forms.Control[] {this.button1} );}

Page 10: 3_Lap Trinh GUI

GUI programGUI program:

main(){

decl data storage;initialization code;

create GUI;register callbacks;

main event loop;}

Callback1() //button1 press{ code;}Callback2() //button2 press{ code;}…

• User input commands

• Non-linear execution

• Unpredictable order

• Much idle time

• Event callback procs

Page 11: 3_Lap Trinh GUI

GUI Events

WindowSystem

eventloop

App1

OK

Cancel

App2 code:

OKbtn_click() { do stuff;}CancelBtn_click(){ do different stuff;}App2Form_click(){ do other stuff;}

mouseclick

inputdevice

App1

eventloop

App2

eventloop

whichapp?

whichcontrol?

App2

OK

Cancel

Page 12: 3_Lap Trinh GUI

C# WinAppC# WinApp:

Class{ decl data storage;

constructor(){initialization code;create GUI controls;register callbacks;

} main(){

Run(new ) } callback1(){

do stuff; } callback2(){

do stuff; }…

• “delegates” = callbacks

• Function pointers

• Listeners

Page 13: 3_Lap Trinh GUI

Delegates

1. Đăng ký control để nhận events• Gắn vào Control một function pointer để gọi callback function• this.button1.Click += new

EventHandler(this.button1_Click);

2. Nhận events từ control• Control sẽ gọi function pointer • private void button1_Click(object sender, EventArgs e){

Button1 Button1_click() callback

click

2. button1_Click( )

1. button1.Click += button1_click( )

Page 14: 3_Lap Trinh GUI

Cơ chế hoạt động Form

Page 15: 3_Lap Trinh GUI

Tạo Form

public class MyForm : System.Windows.Forms.Form {

public MyForm( )

{

Text = "Hello World";

}

public static void Main( )

{

System.Windows.Forms.Application.Run(new MyForm( ));

} }

Tất cả ứng dụng Windows Forms dẫn xuất từ lớp System.Windows.Forms.Form. Một ứng dụng Win forms được tạo như sau:

Page 16: 3_Lap Trinh GUI

• Hình sau đây là ví dụ về giao diện một cửa sổ đăng nhập:

Giới thiệu về window form

Page 17: 3_Lap Trinh GUI

Vi dụ Form Loadstatic int x = 200; static int y = 200; private void Button1_Click(System.Object sender, System.EventArgs

e) { // Create a new Form1 and set its Visible property to true. Form1 form2 = new Form1();form2.Visible = true; // Set the new form's desktop location so it // appears below and to the right of the current form. form2.SetDesktopLocation(x, y); x += 30; y += 30; // Keep the current form active by calling the Activate // method. this.Activate(); this.Button1.Enabled = false;

}

Page 18: 3_Lap Trinh GUI

Các thuộc tính/phương thức của window form

Dùng để thay đổi giao diện của Form lúc chạy chương trình.

Các thuộc tính thông dụng của window form:

• Name

• BackColor

• BackgroundImage

• Font

• Size

• StartPosition

• Text

• WindowState

Các phương thức:• Show• Close• Activate• Hide• Visible

Page 19: 3_Lap Trinh GUI

KiỂU TRÌNH BÀY

• Kiểu trình bày cố định– Thuộc tính Location: là 1 đối tượng của

System.Drawing.Point, góc trên bên trái– Thuộc tính Size: là 1 đối tượng của

System.Drawing.Size

• Kiểu trình bày động– Anchoring– Docking

Page 20: 3_Lap Trinh GUI

KiỂU TRÌNH BÀY CỐ ĐỊNHvoid InitializeComponent() {

this.nameLabel = new Label();

this.nameTextBox = new TextBox();

this.occupationLabel = new Label();

this.occupationTextBox = new TextBox();

// nameLabel

this.nameLabel.Location = new Point(12, 15);

this.nameLabel.Size = new Size(34, 13);

// nameTextBox

this.nameTextBox.Location = new Point(79, 12);

this.nameTextBox.Size = new Size(110, 20);

// occupationLabel

this.occupationLabel.Location = new Point(12, 42);

this.occupationLabel.Size = new.Size(61, 13);

// occupationTextBox

this.occupationTextBox.Location = new Point(79, 39);

this.occupationTextBox.Size = new Size(110, 20);

}

Page 21: 3_Lap Trinh GUI

KiỂU TRÌNH BÀY ĐỘNG• Anchoring

Page 22: 3_Lap Trinh GUI

KiỂU TRÌNH BÀY ĐỘNG

• Docking

Page 23: 3_Lap Trinh GUI

Sự kiện được sinh ra khi người dùng thao tác trên window form ví dụ như người dùng click chuột, gõ phím…Chương trình sẽ bắt các sự kiện này để đáp ứng lại yêu cầu người dùng.

Mỗi control có một danh sách các sự kiện đi kèm theo.

Các sự kiện có sẵn trong window form là:

• Click

• Closed

• Deactivate

• Load

• MouseMove

• MouseDown

• MouseUp

Sự kiện trong Window Form

Page 24: 3_Lap Trinh GUI

Event handler: là phương thức dùng để xử lý sự kiện.

Sự kiện trong Window Form (tt)

using System; using System.Windows.Forms;

public class MyForm : Form {

void btn1_onclick(object sender, EventArgs e)

{ Text = "Sender: " + sender.ToString( ) + " - Event: " + e.ToString( ); }

public MyForm( ) {

Text = "Hello World";

Button btn1 = new Button( );

btn1.Text = "Click Me";

this.Controls.Add(btn1);

btn1.Click += new EventHandler(btn1_onclick); }

public static void Main( ) {

Application.Run(new MyForm( )); } }

Page 25: 3_Lap Trinh GUI

Ví dụ sau đây thể hiện đoạn mã của event handler

private void ClickHandler(object sender, System.EventArgs e) { MessageBox.Show("Clicked!","My Windows Form",MessageBoxButtons.OK); }

Sender: là đối tượng phát sinh sự kiện.

e: dữ liệu được gởi kèm theo với sự kiện.

Sự kiện trong Window Form (tt)

Page 26: 3_Lap Trinh GUI

Phương thức trong window form

Window form có các phương thức cho phép bạn thực hiện một số thao tác như mở form, đóng form, load form…

Các phương thức thường được sử dụng:

•Show()

•Activate()

•Close()

•SetDesktopLocation()

Page 27: 3_Lap Trinh GUI

public void CreateMyForm() { Form form1 = new Form(); // Tạo thể hiện cho FormButton button1 = new Button (); // Tạo buttonButton button2 = new Button (); button1.Text = "OK"; button1.Location = new Point (10, 10); // // Set the text of button2 to "Cancel". button2.Text = "Cancel"; button2.Location = new Point (button1.Left, button1.Height + button1.Top + 10); // Set the caption bar text of the form. form1.Text = "My Dialog Box"; form1.HelpButton = true; form1.FormBorderStyle = FormBorderStyle.FixedDialog; form1.MaximizeBox = false; form1.MinimizeBox = false; form1.AcceptButton = button1; form1.CancelButton = button2; // Set the start position of the form to the center of the screen. form1.StartPosition = FormStartPosition.CenterScreen; // Add button1 to the form. form1.Controls.Add(button1); // Add button2 to the form. form1.Controls.Add(button2); // Display the form as a modal dialog box.

form1.ShowDialog(); }

Page 28: 3_Lap Trinh GUI

2.CONTROLS

Page 29: 3_Lap Trinh GUI

GIỚI THIỆU

• Là đơn vị cơ sở để tạo nên giao diện người dùng trong lập trình WinForm.

• Là bất kỳ đối tượng nào nằm trong vùng chứa của Container có khả năng tương tác với người sử dụng.

Page 30: 3_Lap Trinh GUI

GIỚI THIỆULà đối tượng dùng để nhận dữ liệu được

nhập vào hoặc xuất dữ liệu trên window form.

Các control có các đặc điểm, các phương thức và các sự kiện riêng cho control đó.

Có thể được thêm vào window form từ thanh công cụ.

Page 31: 3_Lap Trinh GUI

• Hình sau đây mô tả một số form control thường gặp:

GIỚI THIỆU

Page 32: 3_Lap Trinh GUI

Các lớp cơ sở • System.Windows.Forms.Control -chứa chức năng cơ bản của thao

tác xử lý bàn phím và nhập từ chuột và xử lý tin nhắn window. • System.Windows.Forms.ButtonBase - Lớp này hỗ trợ chức năng cơ

bản của một nút• System.Windows.Forms.TextBoxBase - cung cấp chức năng và

thuộc tính thông thuờng cho các lớp thừa hưởng. Cả hai lớp TextBox và RichTextBox sử dụng chức năng cung cấp bởi TextBoxBase.

• System.Windows.Forms.ScrollableControl - quản lý sự phát sinh và hiển thị của các thanh cuộn đến người dùng để truy cập đến gốc của một hiển thị.

• System.Windows.Forms.ContainerControl - Lớp này quản lý chức năng yêu cầu cho một control để hành động

• System.Windows.Forms.Panel - có thể chứa các control thêm vào, nhưng khác với lớp ContainerControl, nó phân loại các control một cách đơn giản.

• System.Windows.Forms.Form - Tạo bất kỳ loại cửa sổ nào: standard, toolbox, borderless, modal dialog boxes và multi-document interfaces.

• System.Windows.Forms.UserControl - tạo một custom control đến việc được dùng trong một nơi phức tạp trong một ứng dụng hay tổ chức

Page 33: 3_Lap Trinh GUI

STANDARD CONTROL• Một đối tượng control kế thừa trực tiếp/ gián tiếp từ

System.Windows.Forms.Control• Chia làm 3 loại:

– Action control: Button, Toolbar, MenuBar, ContextMenu

– Value control: Label, TextBox, PictureBox– List control: ListBox, ComboBox, DataGrid, TreeView,

– Container control: GroupBox, Panel, ImageList, …– Dialogs:OpenFileDialog, SaveFileDialog,

PrintDialog, etc

Page 34: 3_Lap Trinh GUI

CONTAINER CONTROL

• Có khả năng chứa nhiều controls

• Thuộc tính Controls dùng để chứa danh sách các control

Page 35: 3_Lap Trinh GUI

THUỘC TÍNH CONTROL COLLECTION

• Là tập hợp chứa các đối tượng control

• Sử dụng Add(),Remove(), RemoveAt() để thêm, xoá 1 control

• Sử dụng Contain() để kiểm tra 1 control có nằm trong tập các control của Form không

Form1.Controls.Remove(textbox1);Form1.Controls.Remove(textbox1);

Form1.Controls.Add(textbox1);Form1.Controls.Add(textbox1);

Form1.Controls.Contains(textbox1);Form1.Controls.Contains(textbox1);

Page 36: 3_Lap Trinh GUI

THÊM CONTROL VÀO CONTAINER

• Tạo đối tượng control muốn thêm vào

• Gắn control vào container

CheckBox signatureCheckBox = new CheckBox();// set propertiessignatureCheckBox.Text = "Signature required";signatureCheckBox.Left = 24;signatureCheckBox.Top = 80;

CheckBox signatureCheckBox = new CheckBox();// set propertiessignatureCheckBox.Text = "Signature required";signatureCheckBox.Left = 24;signatureCheckBox.Top = 80;

// add the new control to the collectionGroupBox1.Controls.Add(signatureCheckBox);

// add the new control to the collectionGroupBox1.Controls.Add(signatureCheckBox);

Page 37: 3_Lap Trinh GUI

LAYOUT CONTROLS

• SplitContainer

Page 38: 3_Lap Trinh GUI

LAYOUT CONTROLS

• GroupBox

Page 39: 3_Lap Trinh GUI

LAYOUT CONTROLS

• FlowLayout

Page 40: 3_Lap Trinh GUI

LAYOUT CONTROLS

• TableLayoutPanel

Page 41: 3_Lap Trinh GUI

ACTION CONTROL

• Sẽ kích hoạt một thao tác nào đó trong chương trình khi được chọn.

• Loại sự kiện chính là Action Event

Page 42: 3_Lap Trinh GUI

Dùng để thực hiện một hành động khi người dùng click chuột vào nó.

Button control có thuộc tính Text để thể hiện thông tin cho button.

Thuộc tính Text này có thể được hiển thị động:

GroupBox1.Text = “Select Gender”

Button

Page 43: 3_Lap Trinh GUI

Button

• Một số thuộc tính cơ bản– Text– TextAlign– BackColor– BackgroundImage– DialogResult

• Một số sự kiện cơ bản– Click– Mouse-up– Mouse-down

Page 44: 3_Lap Trinh GUI

Tạo Button trên Formclass MyForm : Form { //Data member to hold Button control private Button BigButton; public MyForm() {

//Set the properties for the Button BigButton = new Button(); BigButton.Location = new System.Drawing.Point(50, 50); BigButton.Name = "BigButton"; BigButton.Size = new System.Drawing.Size(100, 100); BigButton.Text = "Click Me!"; BigButton.Click += new EventHandler(ClickHandler); //Set properties of the Form itself ClientSize = new System.Drawing.Size(200, 200); Controls.Add(BigButton); Text = "My Windows Form!";

}

Page 45: 3_Lap Trinh GUI

VALUE CONTROL

• Dùng để hiển thị và chỉnh sửa các giá trị.

• Có 08 loại:– String Values: Label, TextBox, StatusBar– Numeric Values: NumericUpDown, HSrollBar,

VScrollBar– Boolean Values: CheckBox, RadioButton– Date Values: DateTimePicker,

MonthCalendar– Graphic Values: PictureBox,

PrintPreviewControl

Page 46: 3_Lap Trinh GUI

TextBox control dùng để hiển thị text hoặc là chấp nhận input từ phía người dùng.

Mặc định TextBox control cho phép hiển thị tối đa 2048 ký tự.

Các thuộc tính thông dụng

•Text

•MultiLine

•PasswordChar

TextBox control

• Vi dụ: Thêm Textbox vào Form

private void button1_Click(object sender, System.EventArgs e) {

TextBox myText = new TextBox(); myText.Location = new Point(25,25); this.Controls.Add (myText);

}

Page 47: 3_Lap Trinh GUI

TextBox• Một số thuộc tính cơ bản

– Text– TextLength– TextAlign– Lines– MultiLine– PasswordChar– ReadOnly– Anchor– Dock– BackColor– BorderStyle– CharacterCasing– ScrollBars– SelectedText – SelectionStart – SelectionLength

Page 48: 3_Lap Trinh GUI

TextBox• Một số phương thức cơ bản

– AppendText – Clear – Copy – Cut – Paste – Undo – GetCharIndexFromPosition – Select

• Một số sự kiện cơ bản– TextChanged

Page 49: 3_Lap Trinh GUI

Label control được dùng để cung cấp thông tin hoặc là mô tả cho control khác trong window form. Label control không cho phép người dùng nhập dữ liệu vào.

Một số các thuộc tính thông dụng:

•Text

•AutoSize

Label control

Page 50: 3_Lap Trinh GUI

Label• Một số thuộc tính cơ bản

– Text– TextAlign– Anchor– Dock– BackColor– BorderStyle– AutoSize– AutoEllipsis– Font– ForeColor– Image

Page 51: 3_Lap Trinh GUI

1: using System;

2: using System.Windows.Forms;

3: using System.Drawing;

4: 5: namespace TYWinforms.Day2 {

6: 7: public class Calculator : Form {

8: private Button btnAdd;

9: private TextBox tbNumber1;

10: private TextBox tbNumber2;

11: private Label lblAnswer;

12: 13: public static void Main() {

14: Application.Run(new Calculator());

15: }

16: 17: public Calculator() {

18: this.btnAdd = new Button();

19: this.tbNumber1 = new TextBox();

20: this.tbNumber2 = new TextBox();

21: this.lblAnswer = new Label();

22: 23: tbNumber1.Location = new Point(0,0); 24: tbNumber2.Location = new Point(100,0); 25: 26: btnAdd.Location = new Point(0,25);

Page 52: 3_Lap Trinh GUI

27: btnAdd.Text = "Add"; 28: btnAdd.Click += new EventHandler(this.Add); 29: 30: lblAnswer.Location = new Point(0,75); 31: 32: this.Controls.Add(btnAdd); 33: this.Controls.Add(tbNumber1); 34: this.Controls.Add(tbNumber2); 35: this.Controls.Add(lblAnswer); 36: } 37: 38: public void Add(object Sender, EventArgs e) { 39: lblAnswer.Text = Convert.ToString(Convert.ToInt32 40: (tbNumber1.Text) + Convert.ToInt32(tbNumber2.Text)); 41: } 42: } 43: }

Page 53: 3_Lap Trinh GUI

LIST CONTROL

• Có thể hiển thị nhiều giá trị cùng lúc

• Mỗi list control có thuộc tính Items chứa danh sách các danh mục.

Page 54: 3_Lap Trinh GUI

ListBox control được dùng để hiển thị danh sách các phần tử.

Người dùng có thể chọn một hay nhiều phần tử từ list. Bạn có thể thêm phần tử mới vào list thông qua cửa sổ

property editor hoặc là thông qua mã chương trình lúc chạy.

Các thuộc tính thường gặp:

• SelectionMode

• Sorted

• SelectedIndex

• SelectedItem

• Items

ListBox control

Page 55: 3_Lap Trinh GUI

1,2,3 // Program to add, remove and clear list box items.

4 using System;

5 using System.Drawing;

6 using System.Collections;

7 using System.ComponentModel;

8 using System.Windows.Forms;

9 using System.Data;

10

11 public class ListBoxTest : System.Windows.Forms.Form

12 {

13 // contains user-input list of elements

14 private System.Windows.Forms.ListBox displayListBox;

15

16 // user input textbox

17 private System.Windows.Forms.TextBox inputTextBox;

18

19 // add, remove, clear and exit command buttons

20 private System.Windows.Forms.Button addButton;

21 private System.Windows.Forms.Button removeButton;

22 private System.Windows.Forms.Button clearButton;

23 private System.Windows.Forms.Button exitButton;

24

25 [STAThread]

26 static void Main()

27 {

28 Application.Run( new ListBoxTest() );

29 }

Display ListBox

Text field for input

Add button

Clear button

Exit button

Page 56: 3_Lap Trinh GUI

31 // add new item (text from input box)

32 // and clear input box

33 private void addButton_Click(

34 object sender, System.EventArgs e )

35 {

36 displayListBox.Items.Add( inputTextBox.Text );

37 inputTextBox.Clear();

38 }

39

40 // remove item if one selected

41 private void removeButton_Click(

42 object sender, System.EventArgs e )

43 {

44 // remove only if item selected

45 if ( displayListBox.SelectedIndex != -1 )

46 displayListBox.Items.RemoveAt(

47 displayListBox.SelectedIndex );

48 }

Add eventhandler

Add method

Remove method

Test if item is selected

Page 57: 3_Lap Trinh GUI

49

50 // clear all items

51 private void clearButton_Click(

52 object sender, System.EventArgs e )

53 {

54 displayListBox.Items.Clear();

55 }

56

57 // exit application

58 private void exitButton_Click(

59 object sender, System.EventArgs e )

60 {

61 Application.Exit();

62 }

63

64 } // end class ListBoxTest

Clear method

Exit

Page 58: 3_Lap Trinh GUI

ListBoxTest.cs Program Output

Page 59: 3_Lap Trinh GUI

Dùng để hiển thị danh sách các phần tử, tuy nhiên ComboBox hiển thị các danh sách này theo kiểu drop – down.

ComboBox có cho phép người dùng nhập dữ liệu vào.

Các phần tử trong ComboBox có thể được thêm vào thông qua property editor hoặc mã chương trình lúc chạy.

Một số các thuộc tính thông dụng:

• Text

• Sorted

• SelectedIndex

• SelectedItem

ComboBox control

Page 60: 3_Lap Trinh GUI

ComboBoxComboBox events and properties

Description / Delegate and Event Arguments

Common Properties

DropDownStyle Determines the type of combo box. Value Simple means that the text portion is editable and the list portion is always visible. Value DropDown (the default) means that the text portion is editable but an arrow button must be clicked to see the list portion. Value DropDownList means that the text portion is not editable and the arrow button must be clicked to see the list portion.

Items Collection of items in the ComboBox control.

MaxDropDownItems Maximum number of items to display in the drop-down list (between 1 and 100). If value is exceeded, a scroll bar appears.

SelectedIndex Returns index of currently selected item. If there is no currently selected item, -1 is returned.

SelectedItem Returns reference to currently selected item.

Sorted If true, items appear in alphabetical order. Default false.

Common Events (Delegate EventHandler, event arguments EventArgs)

SelectedIndexChanged Raised when selected index changes (i.e., a check box has been checked or unchecked). Default when control double-clicked in designer.

Fig. 13.15 ComboBox properties and events.

Page 61: 3_Lap Trinh GUI

ComboBox

ComboBox.

Page 62: 3_Lap Trinh GUI

CheckBox control dùng để hiển thị Yes/No hay đúng/sai.

Các thuộc tính thường dùng:

•Text

•Checked

CheckBox control cho phép người dùng chọn nhiều hơn 1 lựa chọn

CheckBox control

Page 63: 3_Lap Trinh GUI

Dùng để cho người dùng chọn một lựa chọn.

Trong một nhóm, chỉ có một RadioButton được chọn.

Các thuộc tính thường được sử dụng:

•Text

•Checked

RadioButton control

Page 64: 3_Lap Trinh GUI

CUSTOM CONTROL

• Control do người dùng tự xây dựng

• Có 3 loại:– Kế thừa trực tiếp từ lớp

System.Windows.Forms.Control– Kế thừa từ lớp

System.Windows.FormsScrollingControl– Kế thừa từ một control đã có

Page 65: 3_Lap Trinh GUI

• 1 // Fig. 13.38: VisualInheritance.cs• 2 // Base Form for use with visual inheritance• 3 using System;• 4 using System.Drawing;• 5 using System.Collections;• 6 using System.ComponentModel;• 7 using System.Windows.Forms;• 8 using System.Data;• 9 • 10 public class VisualInheritance : System.Windows.Forms.Form• 11 {• 12 private System.Windows.Forms.Label bugsLabel;• 13 private System.Windows.Forms.Button learnMoreButton;• 14 private System.Windows.Forms.Label label1;• 15 • 16 [STAThread]• 17 static void Main() • 18 {• 19 Application.Run( new VisualInheritance() );• 20 }• 21 • 22 private void learnMoreButton_Click( object sender, • 23 System.EventArgs e )• 24 {• 25 MessageBox.Show( • 26 "Bugs, Bugs, Bugs is a product of Bug2Bug.com", • 27 "Learn More", MessageBoxButtons.OK, • 28 MessageBoxIcon.Information );• 29 }• 30 }

Page 66: 3_Lap Trinh GUI

• 1 // Fig. 13.40: VisualInheritanceTest.cs

• 2 // Derived Form using visual inheritance.

• 3 using System;

• 4 using System.Collections;

• 5 using System.ComponentModel;

• 6 using System.Drawing;

• 7 using System.Windows.Forms;

• 8

• 9 public class VisualInheritanceTest :

• 10 VisualInheritance.VisualInheritance

• 11 {

• 12 private System.Windows.Forms.Button learnProgramButton;

• 13

• 14 // invoke when user clicks Learn the Program Button

• 15 private void learnProgramButton_Click( object sender,

• 16 System.EventArgs e )

• 17 {

• 18 MessageBox.Show(

• 19 "This program was created by Deitel & Associates",

• 20 "Learn the Program", MessageBoxButtons.OK,

• 21 MessageBoxIcon.Information );

• 22 }

• 23

• 24 public static void Main( string[] args )

• 25 {

• 26 Application.Run( new VisualInheritanceTest() );

• 27 }

• 28 }

Không thể thay đổi

Có thể thay đổi

Page 67: 3_Lap Trinh GUI

USER CONTROL

• Được tạo ra bằng cách kết hợp các control hiện có

• Một user control kế thừa từ lớp System.Windows.Forms.UserControl

Page 68: 3_Lap Trinh GUI

• 1 // Fig. 13.42: ClockUserControl.cs• 2 // User-defined control with a timer and a label.• 3 • 4 using System;• 5 using System.Collections;• 6 using System.ComponentModel;• 7 using System.Drawing;• 8 using System.Data;• 9 using System.Windows.Forms;• 10 • 11 public class ClockUserControl • 12 : System.Windows.Forms.UserControl• 13 {• 14 private System.Windows.Forms.Timer clockTimer;• 15 private System.Windows.Forms.Label displayLabel;• 16 • 17 // update label at every tick• 18 private void clockTimer_Tick(• 19 object sender, System.EventArgs e )• 20 {• 21 // get current time (Now), convert to string• 22 displayLabel.Text = DateTime.Now.ToLongTimeString();• 23 • 24 } // end method clockTimer_Tick• 25 • 26 } // end class ClockUserControl

Page 69: 3_Lap Trinh GUI

3.MENU

Page 70: 3_Lap Trinh GUI

Menu• Nhóm các lệnh liên quan với nhau

• Gồm:– Commands– Submenus

• Exit dùng Application class để thoát

• Color chọn lựa duy nhất

• Mỗi chọn lựa có event handler của nó

• Kiểu Font tùy chọn dùng Xor operator

Page 71: 3_Lap Trinh GUI

Menu

Fig. 13.1 Expanded and checked menus.

Shortcut key

Disabled command

Separator bar

Menu

submenu

Checked menu item

Page 72: 3_Lap Trinh GUI

Menu

Fig. 13.2 Visual Studio .NET Menu Designer.

Text boxes used to add items to menu

MainMenu icon

Menu Designer

Place & character before the letter to be underlined

Page 73: 3_Lap Trinh GUI

Menu

MainMenu and MenuItem events and properties

Description / Delegate and Event Arguments

MainMenu Properties

MenuItems Collection of MenuItems for the MainMenu.

RightToLeft Used to display text from right to left. Useful for languages that are read from right to left.

MenuItem Properties

Checked Whether menu item appears checked (according to property RadioCheck). Default false, meaning that the menu item is not checked.

Index Item’s position in parent menu.

MenuItems Collection of submenu items for this menu item.

Page 74: 3_Lap Trinh GUI

Menu

MergeOrder This property sets the position of menu item when parent menu merged with another menu.

MergeType This property takes a value of the MenuMerge enumeration. Specifies how parent menu merges with another menu. Possible values are Add, MergeItems, Remove and Replace.

RadioCheck If true, menu item appears as radio button (black circle) when checked; if false, menu item displays checkmark. Default false.

Shortcut Shortcut key for the menu item (i.e. Ctrl + F9 can be equivalent to clicking a specific item).

ShowShortcut If true, shortcut key shown beside menu item text. Default true.

Text Text to appear on menu item. To make an Alt access shortcut, precede a character with & (i.e. &File for File).

Common Events (Delegate EventHandler, event arguments EventArgs)

Click Raised when item is clicked or shortcut key is used. Default when double-clicked in designer.

Fig. 13.3 MainMenu and MenuItem properties and events.

Page 75: 3_Lap Trinh GUI

1 // Fig 13.4: MenuTest.cs

2 // Using menus to change font colors and styles.

3

4 using System;

5 using System.Drawing;

6 using System.Collections;

7 using System.ComponentModel;

8 using System.Windows.Forms;

9 using System.Data;

10

11 public class MenuTest : System.Windows.Forms.Form

12 {

13 // display label

14 private System.Windows.Forms.Label displayLabel;

15

16 // main menu (contains file and format menu)

17 private System.Windows.Forms.MainMenu mainMenu;

18

19 // file menu

20 private System.Windows.Forms.MenuItem fileMenuItem;

21 private System.Windows.Forms.MenuItem aboutMenuItem;

22 private System.Windows.Forms.MenuItem exitMenuItem;

23

About commandExit command

Page 76: 3_Lap Trinh GUI

24 // format menu

25 private System.Windows.Forms.MenuItem formatMenuItem;

26

27 // color submenu

28 private System.Windows.Forms.MenuItem colorMenuItem;

29 private System.Windows.Forms.MenuItem blackMenuItem;

30 private System.Windows.Forms.MenuItem blueMenuItem;

31 private System.Windows.Forms.MenuItem redMenuItem;

32 private System.Windows.Forms.MenuItem greenMenuItem;

33 34 // font submenu35 private System.Windows.Forms.MenuItem timesMenuItem;36 private System.Windows.Forms.MenuItem courierMenuItem;37 private System.Windows.Forms.MenuItem comicMenuItem;38 private System.Windows.Forms.MenuItem boldMenuItem;39 private System.Windows.Forms.MenuItem italicMenuItem;40 private System.Windows.Forms.MenuItem fontMenuItem;41 42 private System.Windows.Forms.MenuItem separatorMenuItem;43

About commandExit command

Color options

Page 77: 3_Lap Trinh GUI

44 [STAThread]

45 static void Main()

46 {

47 Application.Run( new MenuTest() );

48 }

49

50 // display MessageBox

51 private void aboutMenuItem_Click(

52 object sender, System.EventArgs e )

53 {

54 MessageBox.Show(

55 "This is an example\nof using menus.",

56 "About", MessageBoxButtons.OK,

57 MessageBoxIcon.Information );

58 }

59

60 // exit program

61 private void exitMenuItem_Click(

62 object sender, System.EventArgs e )

63 {

64 Application.Exit();

65 }

66

Font options

Style optionsAbout eventhandler

Exit eventHandler

Page 78: 3_Lap Trinh GUI

67 // reset color

68 private void ClearColor()

69 {

70 // clear all checkmarks

71 blackMenuItem.Checked = false;

72 blueMenuItem.Checked = false;

73 redMenuItem.Checked = false;

74 greenMenuItem.Checked = false;

75 }

76

77 // update menu state and color display black

78 private void blackMenuItem_Click(

79 object sender, System.EventArgs e )

80 {

81 // reset checkmarks for color menu items

82 ClearColor();

83

84 // set color to black

85 displayLabel.ForeColor = Color.Black;

86 blackMenuItem.Checked = true;

87 }88

Black eventhandler

Page 79: 3_Lap Trinh GUI

89 // update menu state and color display blue

90 private void blueMenuItem_Click(

91 object sender, System.EventArgs e )

92 {

93 // reset checkmarks for color menu items

94 ClearColor();

95

96 // set color to blue

97 displayLabel.ForeColor = Color.Blue;

98 blueMenuItem.Checked = true;

99 }

100 101 // update menu state and color display red102 private void redMenuItem_Click(103 object sender, System.EventArgs e )104 {105 // reset checkmarks for color menu items106 ClearColor();107 108 // set color to red109 displayLabel.ForeColor = Color.Red;110 redMenuItem.Checked = true;111 }112

Blue eventHandler

Red eventhandler

Page 80: 3_Lap Trinh GUI

113 // update menu state and color display green

114 private void greenMenuItem_Click(

115 object sender, System.EventArgs e )

116 {

117 // reset checkmarks for color menu items

118 ClearColor();

119

120 // set color to green

121 displayLabel.ForeColor = Color.Green;

122 greenMenuItem.Checked = true;

123 }

124

125 // reset font types

126 private void ClearFont()

127 {

128 // clear all checkmarks

129 timesMenuItem.Checked = false;

130 courierMenuItem.Checked = false;

131 comicMenuItem.Checked = false;

132 }

133

Green eventhandler

Page 81: 3_Lap Trinh GUI

134 // update menu state and set font to Times

135 private void timesMenuItem_Click(

136 object sender, System.EventArgs e )

137 {

138 // reset checkmarks for font menu items

139 ClearFont();

140

141 // set Times New Roman font

142 timesMenuItem.Checked = true;

143 displayLabel.Font = new Font(

144 "Times New Roman", 14, displayLabel.Font.Style );

145 }

146

147 // update menu state and set font to Courier

148 private void courierMenuItem_Click(

149 object sender, System.EventArgs e )

150 {

151 // reset checkmarks for font menu items

152 ClearFont();

153

154 // set Courier font

155 courierMenuItem.Checked = true;

156 displayLabel.Font = new Font(

157 "Courier New", 14, displayLabel.Font.Style );

158 }

Times New Roman event handler

Courier Newevent handler

Page 82: 3_Lap Trinh GUI

159 160 // update menu state and set font to Comic Sans MS

161 private void comicMenuItem_Click(

162 object sender, System.EventArgs e )

163 {

164 // reset checkmarks for font menu items

165 ClearFont();

166 167 // set Comic Sans font168 comicMenuItem.Checked = true;169 displayLabel.Font = new Font( 170 "Comic Sans MS", 14, displayLabel.Font.Style );171 }172 173 // toggle checkmark and toggle bold style174 private void boldMenuItem_Click(175 object sender, System.EventArgs e )176 {177 // toggle checkmark178 boldMenuItem.Checked = !boldMenuItem.Checked;179 180 // use Xor to toggle bold, keep all other styles181 displayLabel.Font = new Font( 182 displayLabel.Font.FontFamily, 14,183 displayLabel.Font.Style ^ FontStyle.Bold );184 }

Times New Roman event handler

Courier Newevent handler

Comic Sansevent handler

Bold eventhandler

Page 83: 3_Lap Trinh GUI

185

186 // toggle checkmark and toggle italic style

187 private void italicMenuItem_Click(

188 object sender, System.EventArgs e)

189 {

190 // toggle checkmark

191 italicMenuItem.Checked = !italicMenuItem.Checked;

192

193 // use Xor to toggle bold, keep all other styles

194 displayLabel.Font = new Font(

195 displayLabel.Font.FontFamily, 14,

196 displayLabel.Font.Style ^ FontStyle.Italic );

197 }

198

199 } // end class MenuTest

Italic eventhandler

Page 84: 3_Lap Trinh GUI
Page 85: 3_Lap Trinh GUI

Ví dụ Mã chương trình C#

public class Listing42 : Form {private MainMenu mnuFile = new MainMenu();private Label lblMessage = new Label();

public Listing42() {this.Text = "Listing 4.2";this.Menu = mnuFile;MenuItem miFile = mnuFile.MenuItems.Add("&Windows");miFile.MenuItems.Add(new MenuItem("&Forms"));miFile.MenuItems[0].MenuItems.Add(new MenuItem("&Menus"));miFile.MenuItems[0].MenuItems[0].MenuItems.Add(new

MenuItem("&Are"));miFile.MenuItems[0].MenuItems[0].MenuItems.Add(new

MenuItem("As"));miFile.MenuItems[0].MenuItems[0].MenuItems[1].

MenuItems.Add(new MenuItem("&Easy"));miFile.MenuItems[0].MenuItems[0].MenuItems[1].

MenuItems.Add(new MenuItem("As pie"));}

Page 86: 3_Lap Trinh GUI

4.DIALOG

Page 87: 3_Lap Trinh GUI

GIỚI THIỆU

• Dialog là 1 Windows Form đặc biệt dùng để tương tác với người sử dụng và cung cấp các thông báo.

• Dialog là một Windows Form đa năng.

• Dialog chính là 1 Form với thuộc tính FormBorderStyle có giá trị FixedDialog

Page 88: 3_Lap Trinh GUI

GIỚI THIỆU

• Mục đích sử dụng chính của Dialog là trao đổi thông tin với người sử dụng.

• Sau khi lấy được thông tin, trình xử lý của Dialog sẽ lấy thông tin đó thực hiện một công việc khác.

Page 89: 3_Lap Trinh GUI

PHÂN LOẠI DIALOG

MODAL• Phải cung cấp thông

tin trước khi tiếp tục thực hiện chương trình

• Dùng khi cần thu thập thông tin

MODELESS• Có thể tiếp tục sử

dụng chương trình mà không cần phản hồi thông tin trong Dialog

• Dùng khi chỉ đơn thuần thông báo thông tin.

Page 90: 3_Lap Trinh GUI

SỬ DỤNG DIALOG

• MessageBox.Show()TT Kiểu Miêu tả

1 IWin32Window Tham chiếu của cửa sổ phát sinh Dialog

2 String Nội dung được hiển thị trong Dialog (bắt buộc)

3 String Nội dung được hiển thị trên đầu đề Dialog

4 MessageBoxButtons Số lượng và loại nút có trong Dialog

5 MessageBoxIcon Biểu tượng hiển thị trong Dialog

6 MessageBoxDefaultButton Xác định nút mặc định của Dialog

7 MessageBoxOption Lựa chọn khác (DefaultDesktopOnly, ServiceNotification, RightAlign, RtlReading)

Page 91: 3_Lap Trinh GUI

SỬ DỤNG DIALOG

• Thể hiện 1 dialog của VS.Net

• Thể hiện 1 với thông tin riêng

private void button1_Click(object sender, System.EventArgs e)

{ OpenFileDialog1.ShowDialog();}

private void button1_Click(object sender, System.EventArgs e)

{ OpenFileDialog1.ShowDialog();}

public void PerformCalculations() { MessageBox.Show ("The search is now complete",

"My Application", MessageBoxButtons.OKCancel,

MessageBoxIcon.Asterisk);}

public void PerformCalculations() { MessageBox.Show ("The search is now complete",

"My Application", MessageBoxButtons.OKCancel,

MessageBoxIcon.Asterisk);}

Page 92: 3_Lap Trinh GUI

TẠO MỚI DIALOG

• Lớp MessageBox không thể đáp ứng hết nhu cầu của người sử dụng.

• Tạo mới Dialog tương tự như tạo 1 form

• Không chứa phương thức Main()

Page 93: 3_Lap Trinh GUI

LẤY THÔNG TIN PHẢN HỒI

• Sử dụng thuộc tính DialogResult– Abort– Cancel– Ignore– No– None– OK– Retry– Yes

Page 94: 3_Lap Trinh GUI

LẤY THÔNG TIN PHẢN HỒI

• public void DisplayValue()• {• DialogResult userResponse =

openFileDialog1.ShowDialog();• {• if (userResponse == DialogResult.OK)• filePath = openFileDialog1.FileName.ToString();• MessageBox.Show("You successfully opened: '" +

filePath + "'", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information,MessageBoxDefaultButton.Button1);

• }• …• }

• public void DisplayValue()• {• DialogResult userResponse =

openFileDialog1.ShowDialog();• {• if (userResponse == DialogResult.OK)• filePath = openFileDialog1.FileName.ToString();• MessageBox.Show("You successfully opened: '" +

filePath + "'", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information,MessageBoxDefaultButton.Button1);

• }• …• }

Page 95: 3_Lap Trinh GUI

CÁC DIALOG PHỔ BiẾN

• ColorDialog

• FontDialog

• OpenFileDialog

• PageSetupDialog

• PrintDialog

• PrintPreviewDialog

• SaveFileDialog

Page 96: 3_Lap Trinh GUI

Tìm hiểu thêm

ComboBoxes TreeViews ListViews Tab Control