Logo of Vovisoft


Các mẹo vặt trong VB

Gõ vào đầu đề phía bên trái để nhìn thấy các phần chọn. Muốn khép các phần chọn hãy gõ đầu đề thêm một lần hoặc gõ vào đầu đề khác.

VB Tips & Tricks

Forms
Controls
Ngày Giờ
Files
Ðọc từ text file
Log dữ kiện vào Text file
Ðọc viết từ "ini" file
Cho text vào text file

Linh Tinh

Mẹo vặt (tiếng Anh là Tips & Tricks ) là tinh hoa của VB được cô động lại thành những bài ngắn nhắm vào một điểm nào đó để thực hiện một công việc bằng VB.


Làm sao đọc từ một Text file

Sau đây là một thí dụ đọc data từ một Textfile tên "Friends.txt" nằm trong cùng folder với chương trình đang xử lý.

Sub Form_Load()

   Dim strALine as string

   Dim strLocalFolder as string

   Dim strFullPathFileName as string

   strLocalFolder = App.path

   If Right(strLocalFolder,1) <> "\" then

      strLocalFolder = strLocalFolder & "\"

   End If

   strFullPathFileName = strLocalFolder & "Friends.txt"

   Open  strFullPathFileName for input as #1

   lstFriend.Clear  ' Clear ListBox lstFriend

   Do While Not EOF(1)  ' Read till End-Of-File

     Line Input #1, strALine  ' Read a line

     lstFriend.AddItem  strALine  'Add that line to ListBox

   Loop

   Close #1  ' Close the file

End Sub


Làm sao chứa vào một Text file

Sau đây là một thí dụ đọc data từ một Textfile tên "Friends.txt" nằm trong cùng folder với chương trình đang xử lý.

Sub Form_Load()

   Dim i

   Dim strLocalFolder as string

   Dim strFullPathFileName as string

   strLocalFolder = App.path

   If Right(strLocalFolder,1) <> "\" then

      strLocalFolder = strLocalFolder & "\"

   End If

   strFullPathFileName = strLocalFolder & "Friends.txt"

   Open  strFullPathFileName for output as #2

   For i=0 to lstFriend.Listcount-1

     Print #2, lstFriend.List(i)

   Next

   Close #2  ' Close the file

End Sub


Làm sao Log một dữ kiện vào một Text file ?

Nhiều lúc ta cần Log vào trong một LogFile các biến cố xãy ra trong khi nhu liệu đang chạy để sau nầy kiểm lại tình hình.

Sub LogEvent(ByVal GivenFileName, ByVal msg As String, HasFolder As Boolean, IncludeTimeDate As Integer)

  ' Append event message Msg to a text Logfile GivenFileName

  ' If GivenFileName is fullPathName then HasFolder is true

  ' IncludeTimeDate = 0  : No Time or Date

  '                 = 1  :  Prefix with Time

  '                 = 2  : Prefix with Time and Date

  Dim FileNo, LogFileName, theFolder

  If HasFolder Then

    LogFileName = GivenFileName

  Else

    If Right(App.Path, 1) <> "\" Then

      theFolder = App.Path & "\"

    Else

      theFolder = App.Path

    End If

    LogFileName = theFolder & GivenFileName

  End If

  FileNo = FreeFile

  If Dir(LogFileName) <> "" Then

    Open LogFileName For Append As FileNo

  Else

    Open LogFileName For Output As FileNo

  End If

  Select Case IncludeTimeDate

  Case 0  ' No Time or Date

    Print #FileNo, Msg

  Case 1  ' Time only

    Print #FileNo, Format(Now, "hh:nn:ss ") & Msg

  Case 2  ' Date & Time

    Print #FileNo, Format(Now, "dd/mm/yyyy hh:nn:ss ") & Msg

  End Select

  Close FileNo

 End Sub

Coi chừng trường hợp LogEvent được gọi bởi hai Sub khác nhau cùng một lúc. Khi  Sub thứ nhì muốn mở LogFileName thì bị error vì LogFileName đã bị Sub thứ nhất mở rồi.  Trong trường hợp đó ta có thể sữa LogEvent lại cho nó AddItem Msg vào một Listbox rồi giao nhiệm vụ viết xuống File cho một Process chuyên viên thứ ba. 


Làm sao đọc / viết value của một Variable từ một "ini" file ?

Có khi ta muốn đọc value của một variable chứa trong một file có extension là "ini" (còn gọi là configuration file) nằm trong folder C:Windows hay c:WinNT.  Trong file nầy những cặp variable=value nằm trong các sections, mỗi Section header có dạng như [System Var].  Thí dụ "protocol.ini" chứa ngững dòng sau:

  [ndishlp$]   <=  section header

  DriverName=ndishlp$  <= cặp variable=value

  [protman$]   <=  section header

  DriverName=protman$   <= cặp variable=value

  priority=ndishlp$   <= cặp variable=value

  [data]   <=  section header

  version=v4.10.1998   <= cặp variable=value

Dùng Function ReadPrivateProfileString sau đây để đọc value của VarName$ dưới section header SectionHeader$ từ file Filename$:

Function ReadPrivateProfileString( SectionHeader$, VarName$, Filename$) As String

' Read data from an Ini file in default Windows directory

' Filename$ : The Ini file name   eg: myProg.ini

' SectionHeader$ : The Section name in Ini file eg: [System Var]

' VarName$  : Variable name whose data value we want to get

   Dim RetStr As String

   RetStr = String(255, Chr(0)) ' Prepare a string of 255 zeros (number).

  'Get Requested Information

   ReadPrivateProfileString = Left(RetStr, GetPrivateProfileString(SectionHeader$, ByVal

  VarName$, "", RetStr, Len(RetStr), Filename$))

End Function

Tương tợ như vậy, ta có thể viết value mới của một variable vào trong một "ini" file như sau:

  Dim ErrCode

  ErrCode = WritePrivateProfileString(SectionHeader$, VarName$,newValue, Filename$)

Nhớ để hai câu tuyên bố cho các API Function ta cần vào một Basic Module:

Public Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long

Public Declare Function WritePrivateProfileString& Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal AppName$, ByVal KeyName$, ByVal keydefault$, ByVal Filename$)