Các bài tập Microsoft .NET 1 phần 2 ppsx

18 379 0
Các bài tập Microsoft .NET 1 phần 2 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Các tập Microsoft NET 19 để in Output Window Dĩ nhiên bạn tiếp tục dùng Immediate Window công tác Debug trước VB6 Chưa hết, VS.NET cho bạn Command Window để ta enter VS.NET commands để manipulate IDE, xử lý macros, v.v Để hiển thị Window bạn dùng menu command View | Other Windows | Command Window Để tiện hơn, bạn drag title bar để chồng lên tab bar Task List Output windows Nếu ta enter command như: File.AddNewProject IDE hiển thị Add New Project dialog VS.NET hổ trợ Macro để bạn record playback chuổi cơng tác Phương tiện Integrated Debugging cho ta Debug Menu, Call Stack Window, Breakpoints Window Watch and Value Display Windows Thường thường bạn Add Reference NET components Nhưng bạn dùng ActiveX (có sẵn VB6) NET application cách Add Reference COM (click Tab COM Add Reference Dialog) .NET gói ActiveX thành NET component (click Yes trả Các tập Microsoft NET 20 lời câu hỏi "Would you like to have a wrapper generated for you?") Ngoài dùng Add Reference Projects để refer đến DLL User developed DLL Demo Program Trong chương trình biểu diễn này, ta dùng giao diện hoàn toàn chữ Việt Ta đánh chữ Việt (Unicode) cho Title Bar, Menu, TextBox, ListBox v.v Nếu bạn cần key input software cho chữ Việt hổ trợ Unicode download VPS, Vietkey hay Unikey Các documents Form, XML v.v NET project Saved với UTF-8 encoding Các tập Microsoft NET 21 Trong program Sở thú Saigon ta có hai Listboxes Khi chạy, bạn drag tên loại thú từ Listbox1 (bên trái) để drop vào Listbox2 (bên phải) Phía Label dùng để hiển thị ngày Có button Lưu trử danh sách để ta save data Listbox2 vào file animal.txt subFolder bin Ngồi bạn dùng Main menu Item Đọc danh sách để Load data từ file animal.txt vào Listbox2 Những components không cần phải lúc runtime Timer, Menu, Tooltip v.v nằm Component Tray (mâm) riêng Muốn Edit MainMenu, click lên MainMenu1 icon đánh trực tiếp vào MainMenu Thêm menuitems cách đánh thẳng vào chỗ có chữ Type Here Lưu ý Tabs bên Editing Area bạn mở nhiều forms Các tập Microsoft NET Edit MainMenu, insert Separator 22 Các tập Microsoft NET 23 Chú ý danh sách References liệt kê Solution Explorer Edit Shortcut cho menu item Các tập Microsoft NET 24 Button chứa hình mà cịn cho bạn chọn vị trí hình button ImageAlign Bạn Anchor Button để dính vào góc form để form resizes Button chạy theo góc form Ở ta click hai Dưới Phải cho chúng trở nên màu đen để chọn Anchor Bottom Right Các tập Microsoft NET 25 Trong lúc thiết kế ta edit List items Listbox cách mở property Items Collection Edit vào trang Walk Through Code Trong NET, classes chia thành nhiều nhóm System.IO, System.XML, System.Data, System.Drawing v.v Ngồi nhóm lại cịn chia thành nhóm con, cháu System.Windows.Forms, System.Windows.Collections, System.Windows.Diagnostics, v.v Mặc dầu Project | Add Reference NET components ta dùng chúng program Các tập Microsoft NET 26 phải biên tên dài System.IO.StreamReader để tránh lẫn lộn Để viết tên class gọn ta dùng Imports Imports System.IO, sau ta cần viết StreamReader đủ Cơng việc Imports gọi importing Namespace (của System.IO) Tương tự thế, để tiếp tục dùng Functions Left, Right, Mid VB6 NET ta thêm câu Imports VB6 = Microsoft.VisualBasic đầu chương trình Sau ta viết: AppPath = VB6.Left(AppPath, Pos) Nguyên program Public Class Form1 Form1 thừa kế standard form class NET Framework nên ta declare: Inherits System.Windows.Forms.Form Imports System.IO Imports VB6 = Microsoft.VisualBasic Public Class Form1 Inherits System.Windows.Forms.Form Dim AppPath As String Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem4.Click End ' Terminate the program End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Obtain the folder where this program EXE resides and initialise tooltip Các tập Microsoft NET 27 Dim AppPath As String Dim Pos As Integer ' Fetch full pathname of the EXE file AppPath = System.Reflection.Assembly.GetExecutingAssembly.Location ' Locate the last slash in the pathname string Pos = InStrRev(AppPath, "/") ' Extract the part up to the backslash AppPath = VB6.Left(AppPath, Pos) ' Initialise the tooltip for Listbox1 ToolTip1.SetToolTip(ListBox1, "Xin nắm kéo tên thú qua Listbox bên phải") End Sub Hãy xem cách viết Event Handler như: Private Sub MenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem4.Click Khác với VB6, có thêm chữ Handles MenuItem4.Click phía cuối để nói handling event Click MenuItem4 Mọi Event Handler passed cho hai parameters: ByVal sender As System.Object ByVal e As System.EventArgs Parameter thứ nhất, sender, Object chủ động chuyện RaiseEvent, cịn e Event có chứa nhiều kiện khác tùy theo tình Khi edit code bạn nhờ Intellisense IDE giúp đỡ cho biết parameter e chứa kiện Trong NET, vấn đề handling event khơng phải điều bí hiểm VB6 Khi control RaiseEvent một, mà Các tập Microsoft NET 28 nhiều controls khác Đăng ký (Register) để Thông báo (Notified) Event xãy Control RaiseEvent gọi Publisher (Nhà Xuất Bản), controls muốn handle event gọi Subcribers (những Người Đặt Mua dài hạn) Dĩ nhiên cách handle event control khác nhau, dầu passed cho hai parameters Các EventHandlers gọi Delegates (những Nhà Đại Diện lãnh trách nhiệm giải cố) Do đó, ta dùng vỏn vẹn EventHandler để handle nhiều Event khác nhau, xuất phát từ nhiều Objects Nói cho đơn giản ra, sau ta đăng ký hay nhiều Delegates (tức EventHandler Subs), Event xảy ra, EventHandler Subs xử lý Nếu bạn thấy khó hiểu đọc thí dụ Tưởng tượng bạn làm biếng nấu ăn nên đặt nhà hàng giao cơm ngày đến tận nhà Có hai cách để bạn nhận "gà-mên" cơm: Người giao cơm để "gà-mên" cơm trước nhà, cạnh bên hộp thư Khi làm về, bạn mang vơ nhà Trong trường hợp bạn xử lý công việc tiện, tức lúc đến nhà Cách có điểm bất lợi hôm bạn làm trể cơm bị thiêu trời nóng Bạn đưa chìa khóa nhà cho người giao cơm giữ Khi giao cơm, người tự động mở cửa vô nhà để "gà-mên" thẳng vào tủ lạnh Trong cách Event GiaoCơm handled EventHandler Sub OpenDoorPutIntoFridge, người giao cơm xử lý, khơng phải bạn Như thế, Subscriber (người ăn cơm tháng giao tận nhà) bạn register EventHandler "Sub OpenDoorPutIntoFridge" với người giao cơm qua Các tập Microsoft NET 29 việc đưa chìa khóa Khi Event "GiaoCơm" xãy ra, người giao cơm tự động executes Sub OpenDoorPutIntoFridge Kỹ thuật giao AddressOf Sub cho Object khác để execute cần cịn có tên CallBack Do đó, lúc runtime (không phải design), để Register EventHandler Sub MenuItem4_Click với system để handle Event Click MenuItem4 ta execute code: AddHandler MenuItem4.Click, AddressOf MenuItem4_Click Lưu ý cách ta dùng control ToolTip1 để register Tooltip Text với Listbox1 Ta dùng control ToopTip1 để register nhiều Tooltip Texts với controls khác TextBox, ComboBox v.v Bạn thay hàng: AppPath = VB6.Left(AppPath, Pos) AppPath = AppPath.SubString(0,Pos) Trong VB6, Visual components form chứa dạng Text diễn tả controls dễ đọc đầu form file, khơng phải VB6 code Trong NET, Visual components form chứa dạng code thật Tức là, khơng có VS.NET ta dùng Notepad viết code sau compile, chạy y hệt trường hợp ta dùng VS.NET Điểm giống Java, ta viết code Notepad dùng Command line để compile link code file với components khác Thí dụ ta viết VB.NET program đơn giản để chạy DOS Console, ta compile sau: Các tập Microsoft NET 30 vbc /t:exe /r:system.dll mysource.vb vbc VisualBasic Compiler, /t: có nghĩa target tức EXE để chạy DOS console /r: có nghĩa reference đến DLL Nếu muốn chạy Windows, ta dùng: vbc /t:winexe /r:system.dll /r:system.windows.forms.dll mysource.vb Bình thường generated code dấu Region để khỏi choán chỗ, hay khêu gợi sửa đổi Click dấu + bên lề trái để mở Region hay Sub/Function Click dấu để đóng lại Đơi ta Edit generated code, bạn nhớ backup code trước, để rủi form khơng thể hiển thị bị error, cho ta trang giấy trắng, ta cịn có đường restore Các tập Microsoft NET 31 Mỗi class có Sub New, gọi Constructor (giống Class_Initialize VB6 class) Sub Dispose, gọi Destructor Đó hai Sub dùng để tạo phá hủy Object Vì Form1 thừa kế từ Standard Form nên Sub New trước hết phải gọi constructor MyBase.New() cha nó, Sub Dispose sau hết phải gọi destructor MyBase.Dispose cha Mở Class View Window Bạn Navigate Code qua Class View DoubleClick lên tên Object hay Sub/Function Class View để mang cursor đến code trang Edit Các tập Microsoft NET 32 Bi u di n DragDrop Code DragDrop, lưu ý ta phải viết thêm Sub ListBox2_DragEnter để handle Event DragEnter Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown ' Start the DragDrop process Dim ItemIndex As Integer Các tập Microsoft NET 33 ' Identify the Listbox item that has mousedown using mouse coordinates ItemIndex = ListBox1.IndexFromPoint(New System.Drawing.Point(e.X, e.Y)) ' Start the DragDrop process passing along the ListboxItem as ListBox1.Items(ItemIndex) ListBox1.DoDragDrop(ListBox1.Items(ItemIndex), DragDropEffects.Copy Or DragDropEffects.Move) End Sub Private Sub ListBox2_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox2.DragEnter ' Apply the copy effect ' AND remember to set the property Allow Drop of Listbox2 to TRUE If (e.Data.GetDataPresent(DataFormats.Text)) Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.None End If End Sub Private Sub ListBox2_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListBox2.DragDrop Dim LItem As String Các tập Microsoft NET 34 ' Obtain the Source ListItem String LItem = e.Data.GetData(DataFormats.Text).ToString ' Add it to Listbox2 ListBox2.Items.Add(LItem) ' Remove the Item from Listbox1 ListBox1.Items.RemoveAt(ListBox1.FindString(LItem)) End Sub Khi Load data vào Listbox ta dùng StreamReader để Open File as Input Khi Save data Listbox vào Text file ta dùng StreamWriter để Open File as Output (hay Append ta cho thêm Option Append=True): Private Sub MenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click ' Read the list of animals from a text file into Listbox2 Dim sr As StreamReader Dim Pos As Integer Dim TStr As String ListBox2.Items.Clear() ' Clear Listbox2 ' Use a StreamReader to open the UTF-8 file to read sr = New StreamReader(AppPath & "animals.txt") ' Read each line in the file ' When the end of the file is reached, return the value "-1" Dim x As String Các tập Microsoft NET 35 While sr.Peek -1 x = sr.ReadLine() ' Read a line ListBox2.Items.Add(x) ' Add it to Listbox2 End While sr.Close() ' Close the file End Sub Private Sub SaveAnimalList() ' Save the content of Listbox2 into a UTF-8 Text file Dim i As Integer Dim sw As StreamWriter ' Open the file to write in UTF-8 mode, using a StreamWriter sw = New StreamWriter(AppPath & "Animals.txt") ' Write each line in the Listbox For i = To ListBox2.Items.Count - sw.WriteLine(ListBox2.Items(i)) Next sw.Close() ' Close the file End Sub Ta hiển thị ngày cách dùng Timer1 Shared Function DateTime.Now formated hai Functions có sẵn ToLongDateString ToLongTimeString Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick ' Display Date and Time every half a second Label3.Text = DateTime.Now.ToLongDateString & " " & DateTime.Now.ToLongTimeString End Sub Bạn hiển thị ngày format khác cách viết: Label3.Text = DateTime.Now.ToString("ddd dd/MM/yyyy hh:mm:ss") để có: WED 18/07/2001 09:16:42 Các tập Microsoft NET Để ý Format string ta dùng MM cho Month mm cho Minute 36 ... forms Các tập Microsoft NET Edit MainMenu, insert Separator 22 Các tập Microsoft NET 23 Chú ý danh sách References liệt kê Solution Explorer Edit Shortcut cho menu item Các tập Microsoft NET 24 ... DateTime.Now.ToLongTimeString End Sub Bạn hiển thị ngày format khác cách viết: Label3.Text = DateTime.Now.ToString("ddd dd/MM/yyyy hh:mm:ss") để có: WED 18 /07 /20 01 09 :16 : 42 Các tập Microsoft NET Để ý Format string ta dùng... reached, return the value " -1" Dim x As String Các tập Microsoft NET 35 While sr.Peek -1 x = sr.ReadLine() '' Read a line ListBox2.Items.Add(x) '' Add it to Listbox2 End While sr.Close() '' Close

Ngày đăng: 31/07/2014, 09:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan