You are on page 1of 47

Tác giả : Lê Nguyên Dũng

Lớp 11C1 trường THPT Đăk Nông (Thị xã Gia Nghĩa - Đ ăk Nông)

Email của mình : le.nguyendung@gmail.com


Nick : nguyen_dung_vb

Địa chỉ nhà : Thôn 1, thị trấn Đăk Mâm Huyện Krông Nô Tỉnh Đắk Nông

Tự hào ghê cái Logo của cuốn sách mình thiết kế bằng ... Word và Paint đấy. Nhìn vô cũng
chuyên nghiệp đấy chứ
Lời nói đầu

Sau khi “Xuất bản” cuốn “Chiêu thức lập trình” mình quả thật rất buồn vì chẳng có lấy một lời
động viên từ bất kỳ ai (Ở Đăk Nông này mình có biết ai mà khoe) còn anh em ở việt nam nét thì
chẳng đoái hoài gì cả vì vậy mình đã thật sự nản, để cuối cùng sau một sự cố nghề nghiệp phiên
bản Chiêu thức lập trình phiên bản 2 mình viết gần hoàn thành bỗng tan vào sương khói mình đã
tuyệt vọng. Nhưng mới hồi sáng khi mình “Viếng” www.caulacbovb.com một diễn đàn mình tham
gia từ khá lâu nhưng không mấy quan tâm mình đã thấy cuốn sách này được chia sẽ trên đó,
cùng với đó là lời khen của một nhân vật mình không nhớ tên đã làm mình rất vui, vì mình đã
nhận ra mình cũng được công nhận dù chỉ một chút. Cuốn Chiêu thức lập trình lần này sẽ được
nâng cấp lên với nhiều chiêu thức và hình vẽ minh hoạ để giúp các bạn nâng cao kiến thức.

Lời cầu cứu : Do từ năm lớp 9 đến nay mình chỉ tập trung vào học lập trình (Mà lại toàn tự học)
nên hiện nay đệ đã học sút rất nhiều nguy cơ rớt đại học ngày một đến gần mà ước mơ lớn nhất
của đời đệ là đậu vào khoa Công Nghệ Thông Tin Đại học Bách Khoa Hồ Chí Minh đệ mong
rằng có huynh nào đã từng phải nếm trải cảnh thi đại học thì chia sẻ kinh nghiệm học, học sách
gì ... Còn nếu có sách vở (Cũ cũng được) không cần dùng tới nhưng tốt để ôn thi đại học thì chia
sẽ cho đệ. Nếu có huynh nào có lòng “Hảo tâm” hãy gửi đến địa chỉ : (Đây là địa chỉ cô giáo dạy
Tin của trường đệ vào hết năm học này có thể thay đổi)
Phạm Thị Loan giáo viên trường Trung Học Phổ Thông Đăk Nông, xin ghi rõ là nhở gửi cho em
Lê Nguyên Dũng lớp 11C1

Cuốn sách này là cuốn sách hoàn toàn miễn phí để chia sẽ trong cộng đồng lập trình nên nếu có
ai múôn sử dụng để in sách thì cũng nên ghi rõ xuất sứ.
Trong sách tôi xin chỉ rõ xuất xứ, mong rằng các ban cũng sẽ tôn trong tác giả không chỉnh sửa
tác giả hay các xuất xứ
Cuốn sách này đi theo định hướng là sử dụng các hàm API hoặc các lệnh đơn giản để tạo thành
những thủ thuật và hạn chế tối đa phải sử dụng các công cụ hỗ trợ.
Mục lục

Đôc chiêu 1 : “Thả một câu từ trên cao xuống” (Có thể nói như vậy)
Đôc chiêu 2 : Hiện một câu bằng cách lần lượt hiện từng chữ
Đôc chiêu 3 : Hiện con trỏ động tại một đối tượng nào đó
Đôc chiêu 4 : Form có hình dạng theo một hình ảnh bất k ỳ
Đôc chiêu 5 : “Chụp ảnh màn hình vào một Picture”
Đôc chiêu 6 : “Vô hiệu hoá button close và menu của form (cả Alt-F4 luôn)”
Đôc chiêu 7 : “Kéo form di chuyển từ một điểm bất kỳ”
Đôc chiêu 8 : “Ghi lại tất cả những phím gõ tên bàn phím”
Đôc chiêu 9 : Đóng một ứng dụng bất kỳ
Đôc chiêu 10 : Tạo phím nóng cho chương trình
Đôc chiêu 11 : Thay đổi hình nền cho Desktop
Đôc chiêu 12 : Đóng mở khay CD-ROM
Đôc chiêu 13 : Tạo một SystemTray cho ứng dụng của bạn
Đôc chiêu 14 : Thay đổi Font tiếng việt cho Menu của Window
Đôc chiêu 15 : So sánh hai ảnh
Đôc chiêu 16 : Liệt kê danh sách các thành phần phần cứng trong máy
Đôc chiêu 17 : Chương trình khởi động cùng với Windowns
Đôc chiêu 18 : Play một file nhạc Midi
Đôc chiêu 19 : Khoá một file ảnh định dạng .bmp
Đôc chiêu 20 : Để form của bạn ở chế độ “Luôn nổi”
Đôc chiêu 21 : TextBox chỉ “Chịu” nhận số
Đôc chiêu 22 : Để form trở nên trong suốt
Đôc chiêu 23 : Lấy tên người sử dung của Windowns
Đôc chiêu 24 : Chép cả màn hình làm việc vào một Picture
Đôc chiêu 25 : Dấu dữ liệu dạng text vào 1 file bất kỳ
Đôc chiêu 26 :Mở từng hộp thoại trong Control Panel
Đôc chiêu 27 : Mã hoá dữ liệu dạng text
Đôc chiêu 1 : “Thả một câu từ trên cao xuống” (Có thể nói như vậy) home
Xuất xứ : www.pscode.com
Binh khí sử dụng : Một Picture và một CommandButton
Đoạn mã :
Option Explicit

Private Sub command1_Click()


Randomize Timer 'Init Rnd

'Declarations
Dim StartTime(100) 'Starttime of a up/down
movement
Dim DownMovement(100) As Boolean 'are we doing a up or down
movement ???
Dim MoveDistance As Double 'distance target has moved
since the start of the movement
Dim YPos(100) As Double 'Holds the y position of a
letter
Dim MovementDone(100) As Boolean 'Is set to true when a up /
down movement is completed
Dim StartHeight(100) As Double 'From which hight will
the letter fall down ?
Dim UpMovementTime(100) As Double 'How long will it the
letter take to move up
Dim PowerLoss(100) As Double 'losing xx% of power
when touching the ground
Dim Message As String 'Message you want to display
Dim Looop As Integer 'Loop var
Dim TextColor(100) As ColorConstants 'Color of one letter

'Settings

picture1.ScaleMode = 4
picture1.FontName = "Courier New"

Message = "Ohh my god ! It's raining letters today !!! Contact me:
overkillpage@gmx.net" 'Message you want to display

For Looop = 1 To Len(Message)

PowerLoss(Looop) = 0.2 + ((Rnd * 25) / 100)


'losing xx% of power when touching the ground
StartHeight(Looop) = 0
TextColor(Looop) = RGB(80 + Looop * 2, 80 + Looop * 2, 255)

Next Looop

For Looop = 1 To Len(Message)


StartTime(Looop) = Timer 'Setting up
startime for a following movement, needed for calculation of position
Next Looop

Do

picture1.Cls 'Clear picturebox


'Looping throung the textmessage
For Looop = 1 To Len(Message)

If DownMovement(Looop) = True Then

MoveDistance = (StartHeight(Looop) + (0.5 * 9.81 *


((Timer - StartTime(Looop)) ^ 2))) 'Calculating falling distance

If YPos(Looop) >= picture1.ScaleHeight - 1 Then


MovementDone(Looop) = True 'The letter reached the bottom border.
The Downmovement is complete

Else
MoveDistance = (StartHeight(Looop) + (0.5 * 9.81 *
(UpMovementTime(Looop) - (Timer - StartTime(Looop))) ^ 2)) 'Calculating
falling distance

If YPos(Looop) <= StartHeight(Looop) + 0.1 Then


MovementDone(Looop) = True 'The letter reached the max. height.
The upmovement is complete

End If

YPos(Looop) = MoveDistance

If YPos(Looop) > picture1.ScaleHeight - 1 Then


'If the letter fell picture1 of our picturebox ;) we fix it
YPos(Looop) = picture1.ScaleHeight - 1
'At the bottom position
End If

picture1.CurrentX = picture1.ScaleWidth / 2 -
Int((Len(Message) / 2)) + Looop
picture1.CurrentY = YPos(Looop)
'Setting the letters y position
picture1.ForeColor = TextColor(Looop)
'Setting the letters color
picture1.Print Mid(Message, Looop, 1)
'Text picture1put

Next Looop

DoEvents

For Looop = 1 To Len(Message)

If MovementDone(Looop) = True Then

If DownMovement(Looop) = True Then 'Switch between


up/downmovement
DownMovement(Looop) = False
StartHeight(Looop) = StartHeight(Looop) +
((picture1.ScaleHeight - StartHeight(Looop)) * PowerLoss(Looop)) 'New
Startheight, because of speed lost ?!?!
UpMovementTime(Looop) = Sqr((picture1.ScaleHeight -
StartHeight(Looop)) / (0.5 * 9.81)) 'How long will the NEXT
upmovement last ???
Else
DownMovement(Looop) = True
End If

StartTime(Looop) = Timer 'Set the


StartTime of a new movement
MovementDone(Looop) = False
End If

Next Looop

Loop 'Until StartHeight = picture1.ScaleHeight

End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)


End
End Sub
Đôc chiêu 2 : Hiện một câu bằng cách lần lượt hiện từng chữ home
Xuất xứ : www.pscode.com
Binh khí sử dụng : Một Module , ba CommandButton lần lượt có các tên cmdStart, cmdClear,
cmdExit, thêm hai cái đồng hồ tên là Timer1 (Interval =50) và Timer2(Interval =5) cuối cùng là
một label tên là lblText
Đoạn mã :
Module :
Public ASCC(5) As String
Public Letters() As String
Public TXT As String
Public CurLetter As Integer
Public TEXTT As String
Public r As Integer
Form :
Private Sub cmdClear_Click()
lblText.Caption = ""
End Sub

Private Sub cmdExit_Click()


End
End Sub

Private Sub cmdStart_Click()


TXT = InputBox("Enter Text")

ReDim Preserve Letters(0)


ReDim Preserve Letters(Len(TXT))
lblText = ""
CurLetter = 0

For l = 1 To Len(TXT)
Letters(l) = Mid(TXT, l, 1)
Next

Timer2.Enabled = True
End Sub

Private Sub Form_Load()

End Sub

Private Sub Timer1_Timer()


r = r + 1
lblText.Caption = TEXTT
lblText.Caption = lblText.Caption & "_"
If r = 6 Then
r = 0
If 65 < Asc(Letters(CurLetter)) < 90 Then
lblText.Caption = TEXTT
lblText.Caption = lblText.Caption & Letters(CurLetter)
TEXTT = lblText
Timer2.Enabled = True
Timer1.Enabled = False
Else
lblText.Caption = TEXTT
lblText.Caption = lblText.Caption & Chr$(Asc(Letters(CurLetter)) -
32)
TEXTT = lblText
Timer2.Enabled = True
Timer1.Enabled = False
End If

End If

End Sub

Private Sub Timer2_Timer()


CurLetter = CurLetter + 1

If CurLetter > Len(TXT) Then


GoTo HERE:
End If

TEXTT = lblText
Timer1.Enabled = True
Timer2.Enabled = False

HERE:
Timer2.Enabled = False
End Sub

Đôc chiêu 3 : Hiện con trỏ động tại một đối tượng nào đó home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : Chỉ cần một cái Form
Đoạn mã :

'Hằng được sử dụng


private Const ConTro=(-12)

'Các hàm API được sử dụng


Private Declare Function SetClasslong Lib "user32" Alias
"SetClassLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal
wNewWord As Long) As Long

Private Declare Function LoadCursorFromFile Lib "user32" Alias


"LoadCursorFromFileA" (ByVal lpFileName As String) As Long

Dim NewCur as long


Dim OldCur as long

Private Sub Form_Load


'Giả sử rằng bạn đã có sẵn file Clock.ani ở ổ C:\
NewCur=LoadCursorFromFile("C:\Clock.ani")
OldCur=SetClassLong(Me.hwnd, ConTro,NewCur)
End sub

Private Sub Form_UnLoad(Cancel as Integer)


SetClassLong me.hwnd, Contro,OldCur
End Sub

- Ta rút ra được một “Công thức” : Thay vì đặt con trỏ động trong Form ta có thể thay Me.hwnd
trong dòng lệnh : OldCur=SetClassLong(Me.hwnd, ConTro,NewCur) bằng đối tựợng.hwnd (Nếu
đối tượng đó hổ trợ )

Đôc chiêu 4 : Form có hình dạng theo một hình ảnh bất kỳ (Tất nhiên có màu tượng trưng
cho form trong suốt) home
Xuất xứ : www.pscode.com
Binh khí sử dụng : Chỉ cần một cái Form, trong form c ó s ẵn h ình n ền (Màu đen sẽ là màu chỉ
định trong suốt)
Đoạn mã : Bản thân đoạn mã này cũng có thêm một vài chức năng ngoài nhưng đều rất thích
hợp cho 1 ứng dụng
Option Explicit
Private Declare Function ReleaseCapture Lib "user32" () As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA"
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam
As Any) As Long
Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long,
ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal
cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
Private Const HWND_TOPMOST = -1
Private Const SWP_NOMOVE = &H2
Private Const SWP_NOSIZE = &H1
Private Const Flags = SWP_NOMOVE Or SWP_NOSIZE

'Transparency Declarations and Constants


'I copied these from Robert Gainor's Example
Private Declare Function CreateRectRgn Lib "gdi32" (ByVal X1 As Long,
ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Private Declare Function CombineRgn Lib "gdi32" (ByVal hDestRgn As
Long, ByVal hSrcRgn1 As Long, ByVal hSrcRgn2 As Long, ByVal
nCombineMode As Long) As Long
Private Declare Function OffsetRgn Lib "gdi32" (ByVal hRgn As Long,
ByVal X As Long, ByVal Y As Long) As Long
Private Declare Function SetWindowRgn Lib "user32" (ByVal hwnd As Long,
ByVal hRgn As Long, ByVal bRedraw As Boolean) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hDC As Long,
ByVal hObject As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As
Long) As Long
Private Declare Function DeleteDC Lib "gdi32" (ByVal hDC As Long) As
Long
Private Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hDC As
Long) As Long
Private Declare Function GetPixel Lib "gdi32" (ByVal hDC As Long, ByVal
X As Long, ByVal Y As Long) As Long
Private Const RGN_AND = 1
Private Const RGN_OR = 2
Private Const RGN_XOR = 3
Private Const RGN_DIFF = 4
Private Const RGN_COPY = 5

'FormMove and FormOnTop Subs


Private Sub FormOnTop(Frm As Form)
Call SetWindowPos(Frm.hwnd, HWND_TOPMOST, 0&, 0&, 0&, 0&, Flags)
End Sub

Private Sub FormMoveXP(Frm As Form)


Call ReleaseCapture
Call SendMessage(Frm.hwnd, &HA1, 2, 0&)
End Sub

Private Sub CenterForm(Frm As Form)


Frm.Left = Screen.Width / 2 - Frm.Width / 2
Frm.Top = Screen.Height / 2 - Frm.Height / 2
End Sub

'Transparency Function
'I copied this from Robert Gainor's Example
Private Function MakeTransparent(ByRef Frm As Form, ByVal
TransparentColor As Long) As Long
Dim rgnMain As Long, rgnPixel As Long, bmpMain As Long, dcMain As Long
Dim Width As Long, Height As Long, X As Long, Y As Long
Dim ScaleSize As Long, RGBColor As Long
ScaleSize& = Frm.ScaleMode
Frm.ScaleMode = 3
Frm.BorderStyle = 0
Width& = Frm.ScaleX(Frm.Picture.Width, vbHimetric, vbPixels)
Height& = Frm.ScaleY(Frm.Picture.Height, vbHimetric, vbPixels)
Frm.Width = Width& * Screen.TwipsPerPixelX
Frm.Height = Height& * Screen.TwipsPerPixelY
rgnMain& = CreateRectRgn(0&, 0&, Width&, Height&)
dcMain& = CreateCompatibleDC(Frm.hDC)
bmpMain& = SelectObject(dcMain&, Frm.Picture.Handle)
For Y& = 0& To Height&
For X& = 0& To Width&
RGBColor& = GetPixel(dcMain&, X&, Y&)
If RGBColor& = TransparentColor& Then
rgnPixel& = CreateRectRgn(X&, Y&, X& + 1&, Y& + 1&)
CombineRgn rgnMain&, rgnMain&, rgnPixel&, RGN_XOR
DeleteObject rgnPixel&
End If
Next X&
Next Y&
SelectObject dcMain&, bmpMain&
DeleteDC dcMain&
DeleteObject bmpMain&
If rgnMain& <> 0& Then
SetWindowRgn Frm.hwnd, rgnMain&, True
MakeTransparent = rgnMain&
End If
Frm.ScaleMode = ScaleSize&
End Function

'Form Code
Private Sub Form_Load()
Call FormOnTop(Me)
Call CenterForm(Me)
Call MakeTransparent(Me, CLng(0))
End Sub

Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As


Single, Y As Single)
Call FormMoveXP(Me)
End Sub

Private Sub Form_Unload(Cancel As Integer)


End
End Sub
Đôc chiêu 5 : “Chụp ảnh màn hình vào một Picture” home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : Một Picture và một CommandButton
Đoạn mã :

Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function StretchBlt Lib "gdi32" (ByVal hdc As Long,
ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight
As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long,
ByVal nSrcWidth As Long, ByVal nSrcHeight As Long, ByVal dwRop As Long)
As Long

Private Sub Command1_Click()


Dim wScreen As Long
Dim hScreen As Long
Dim w As Long
Dim h As Long
Picture1.Cls

wScreen = Screen.Width \ Screen.TwipsPerPixelX


hScreen = Screen.Height \ Screen.TwipsPerPixelY

Picture1.ScaleMode = vbPixels
w = Picture1.ScaleWidth
h = Picture1.ScaleHeight

hdcScreen = GetDC(0)
r = StretchBlt(Picture1.hdc, 0, 0, w, h, hdcScreen, 0, 0, wScreen,
hScreen, vbSrcCopy)

End Sub

Đôc chiêu 6 : “Vô hiệu hoá button close và menu của form (cả Alt-F4 luôn)” home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : Chẳng cần gì ta chỉ cần tay không bắt hổ
Đoạn mã :

Private Declare Function DeleteMenu Lib "user32" (ByVal hMenu As Long,


ByVal nPosition As Long, ByVal wFlags As Long) As Long
Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As
Long, ByVal bRevert As Long) As Long

Private Const MF_BYPOSITION = &H400&

Private ReadyToClose As Boolean


Private Sub RemoveMenus(frm As Form, _
remove_restore As Boolean, _
remove_move As Boolean, _
remove_size As Boolean, _
remove_minimize As Boolean, _
remove_maximize As Boolean, _
remove_seperator As Boolean, _
remove_close As Boolean)
Dim hMenu As Long

hMenu = GetSystemMenu(hwnd, False)

If remove_close Then DeleteMenu hMenu, 6, MF_BYPOSITION


If remove_seperator Then DeleteMenu hMenu, 5, MF_BYPOSITION
If remove_maximize Then DeleteMenu hMenu, 4, MF_BYPOSITION
If remove_minimize Then DeleteMenu hMenu, 3, MF_BYPOSITION
If remove_size Then DeleteMenu hMenu, 2, MF_BYPOSITION
If remove_move Then DeleteMenu hMenu, 1, MF_BYPOSITION
If remove_restore Then DeleteMenu hMenu, 0, MF_BYPOSITION
End Sub

Private Sub cmdClose_Click()


ReadyToClose = True
Unload Me
End Sub

Private Sub Form_Load()


RemoveMenus Me, False, False, _
False, False, False, True, True
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)


Cancel = Not ReadyToClose
End Sub
Đôc chiêu 7 : “Kéo form di chuyển từ một điểm bất kỳ” home
Xuất xứ : www.allapi.net
Binh khí sử dụng : Lại cũng tay không tập bắt hổ
Đoạn mã :

Private Declare Function SendMessage Lib "User32" Alias "SendMessageA"


(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam
As Any) As Long
Private Declare Sub ReleaseCapture Lib "User32" ()
Const WM_NCLBUTTONDOWN = &HA1
Const HTCAPTION = 2
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As
Single, Y As Single)
Dim lngReturnValue As Long
If Button = 1 Then
Call ReleaseCapture
lngReturnValue = SendMessage(Me.hWnd, WM_NCLBUTTONDOWN,
HTCAPTION, 0&)
End If
End Sub
Private Sub Form_Paint()
Me.Print "Hay keo tui di"
End Sub

Đôc chiêu 8 : “Ghi lại tất cả những phím gõ tên bàn phím” home
Xuất xứ : www.allapi.net
Binh khí sử dụng : Cần một cái Module
Đoạn mã :
Trong Module :
Public Const DT_CENTER = &H1
Public Const DT_WORDBREAK = &H10
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Declare Function DrawTextEx Lib "user32" Alias "DrawTextExA" (ByVal hDC
As Long, ByVal lpsz As String, ByVal n As Long, lpRect As RECT, ByVal
un As Long, ByVal lpDrawTextParams As Any) As Long
Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal
nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As
Long
Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal
nIDEvent As Long) As Long
Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As
Integer
Declare Function SetRect Lib "user32" (lpRect As RECT, ByVal X1 As
Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
Global Cnt As Long, sSave As String, sOld As String, Ret As String
Dim Tel As Long
Function GetPressedKey() As String
For Cnt = 32 To 128
If GetAsyncKeyState(Cnt) <> 0 Then
GetPressedKey = Chr$(Cnt)
Exit For
End If
Next Cnt
End Function
Sub TimerProc(ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse
As Long, ByVal lpTimerFunc As Long)
Ret = GetPressedKey
If Ret <> sOld Then
sOld = Ret
sSave = sSave + sOld
End If
End Sub
Trong Form :
Private Sub Form_Load()
Me.Caption = "Key Spy"
SetTimer Me.hwnd, 0, 1, AddressOf TimerProc
End Sub
Private Sub Form_Paint()
Dim R As RECT
Const mStr = "Nao bat dau go di khi ban an dau X de thoat ban se
thay bat ngo thu vi day."
Me.Cls
Me.ScaleMode = vbPixels
SetRect R, 0, 0, Me.ScaleWidth, Me.ScaleHeight
DrawTextEx Me.hDC, mStr, Len(mStr), R, DT_WORDBREAK Or DT_CENTER,
ByVal 0&
End Sub
Private Sub Form_Resize()
Form_Paint
End Sub
Private Sub Form_Unload(Cancel As Integer)
KillTimer Me.hwnd, 0
MsgBox sSave
End Sub
Đôc chiêu 9 : Đóng một ứng dụng bất kỳ home
Xuất xứ : www.echip.com.vn (Báo eChip)
Binh khí sử dụng : Cần một cái đồng hồ(Timer) chú ý thuộc tính Interval (Riêng tôi cho là 1)
Gíơi thiệu : Đoạn mã đóng một cửa sổ bất ỳ nào đó dựa vào tên của nó
Đoạn mã :
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA"
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam
As Any) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA"
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Sub tmrkiemtra_Timer()
Do While FindWindow(vbNullString, "Windows Task Manager") <> 0
‘Gia su toi muon “Thu tieu “ hop thoai “Windows Task Manager”
PostMessage FindWindow(vbNullString, "Windows Task Manager"), &H10, 0&,
0&
Loop
End Sub

- Đây là một chiêu thức rất quan trọng của một phần mềm bảo mật nên có thể đang rất cần cho
nhiều bạn. Riêng tôi do quá “Bất mãn” với cái bọn bạn quỷ quái nên đây s ẽ là một trong những
tuyệt chiêu tôi sử dụng để viết Virus (Theo dự tính tiết thực hành thứ 2 tuần tới sẽ có vài cái máy
tính của trường phải “Nhập viện”) he he nhưng tôi không tàn nhẫn tới mức phá hoại đâu tui “Hiền
lắm” chỉ cho bọn bạn gà mờ “Biết ít khoe nhiều trên trường” không “Thực hành” thôi, Chúc các
bạn có những giây phút “Sản khoái” như tôi với độc chiêu này.
Đôc chiêu 10 : Tạo phím nóng cho chương trình : home
Xuất xứ : www.allapi.net
Binh khí sử dụng : Cần một cái Module (Form thì luôn luôn cần rồi)
Đoạn mã : (Bẫy phím Alt+Z)
Trong Module :
Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hwnd As Long, _
ByVal wMsg As Long, ByVal wParam As Long, _
lParam As Long) As Long
Declare Function DefWindowProc Lib "user32" _
Alias "DefWindowProcA" (ByVal hwnd As Long, _
ByVal wMsg As Long, ByVal wParam As Long, _
ByVal lParam As Long) As Long
Public Const WM_SETHOTKEY = &H32
Public Const WM_SHOWWINDOW = &H18
Public Const HK_SHIFTA = &H141 'Shift + A
Public Const HK_SHIFTB = &H142 'Shift * B
Public Const HK_CONTROLA = &H241 'Control + A
Public Const HK_ALTZ = &H45A

'The value of the key-combination has to


'declared in lowbyte/highbyte-format
'That means as a hex-number: the last two
'characters specify the lowbyte (e.g.: 41 = a),
'the first the highbyte (e.g.: 01 = 1 = Shift)
Trong Form :
Private Sub Form_Load()
Me.WindowState = vbMinimized
'Let windows know what hotkey you want for
'your app, setting of lParam has no effect
erg& = SendMessage(Me.hwnd, WM_SETHOTKEY, HK_ALTZ, 0)
'Check if succesfull
If erg& <> 1 Then
MsgBox "You need another hotkey", vbOKOnly, "Error"
End If
'Tell windows what it should do, when the hotkey
'is pressed -> show the window!
'The setting of wParam and lParam has no effect
erg& = DefWindowProc(Me.hwnd, WM_SHOWWINDOW, 0, 0)
End Sub

Đôc chiêu 11 : Thay đổi hình nền cho Desktop home


Xuất xứ : www.caulacbovb.com
Binh khí sử dụng : Một CommandButton
Đoạn mã :
Option Explicit
‘ Các hằng số và hàm phục vụ cho việc thay đổi WallPaper
Private Const SPIF_UPDATEINIFILE = &H1
Private Const SPI_SETDESKWALLPAPER = 20
Private Const SPIF_SENDWININICHANGE = &H2

Private Declare Function SystemParametersInfo Lib "user32" Alias


"SystemParametersInfoA" (ByVal uAction As Long, ByVal uParam As Long, ByVal
lpvParam As Any, ByVal fuWinIni As Long) As Long
‘Phục vụ cho việc ghi giá trị vào Registry
Public Enum REG_TOPLEVEL_KEYS
HKEY_CLASSES_ROOT = &H80000000
HKEY_CURRENT_CONFIG = &H80000005
HKEY_CURRENT_USER = &H80000001
HKEY_DYN_DATA = &H80000006
HKEY_LOCAL_MACHINE = &H80000002
HKEY_PERFORMANCE_DATA = &H80000004
HKEY_USERS = &H80000003
End Enum

Private Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA"


(ByVal Hkey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal Hkey As Long) As
Long
Private Declare Function RegSetValueEx Lib "advapi32.dll" Alias
"RegSetValueExA" (ByVal Hkey As Long, ByVal lpValueName As String, ByVal
Reserved As Long, ByVal dwType As Long, lpData As Any, ByVal cbData As Long) As
Long
Private Const REG_SZ = 1

Public Function ChangeWallPaper(ImageFile As String, Optional Tile As Boolean =


True, Optional Center As Boolean = True) As Boolean
Dim lRet As Long
On Error Resume Next
If Tile Then 'Kieu Tile
WriteStringToRegistry HKEY_CURRENT_USER, "Control Panel\desktop",
"TileWallpaper", "1"
Else 'Center or Stretch
WriteStringToRegistry HKEY_CURRENT_USER, "Control Panel\desktop",
"TileWallpaper", "0"
'Center
If Center Then WriteStringToRegistry HKEY_CURRENT_USER, "Control
Panel\desktop", "WallpaperStyle", "0" _
Else: WriteStringToRegistry HKEY_CURRENT_USER, "Control Panel\desktop",
"TileWallpaper", "2" ' Stretch
End If
lRet = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, ImageFile,
SPIF_UPDATEINIFILE Or SPIF_SENDWININICHANGE)
ChangeWallPaper = lRet <> 0
End Function

Private Function WriteStringToRegistry(Hkey As REG_TOPLEVEL_KEYS, strPath As


String, strValue As String, strdata As String) As Boolean
Dim bAns As Boolean
On Error GoTo ErrorHandler
Dim keyhand As Long
Dim r As Long
r = RegCreateKey(Hkey, strPath, keyhand)
If (r = 0) Then
r = RegSetValueEx(keyhand, strValue, 0, REG_SZ, ByVal strdata, Len(strdata))
r = RegCloseKey(keyhand)
End If
WriteStringToRegistry = (r = 0)
Exit Function
ErrorHandler:
WriteStringToRegistry = False
MsgBox "Thay doi gia tri Registry khong thanh cong", , "Loi :"
End Function

Private Sub Command1_Click()


‘ Load file ảnh cần thiết
ChangeWallPaper "C:\Ben Tre.bmp" ‘Kiểu Tile
‘ChangeWallPaper "C:\Ben Tre.bmp", False ‘Kiểu Center
‘ChangeWallPaper "C:\Ben Tre.bmp", False, False ‘Kiểu Stretch
End Sub

Đôc chiêu 12 : Đóng mở khay CD-ROM home


Xuất xứ : www.caulacbovb.com
Lưu ý: Chương trình này chỉ tác dụng tới ổ CD đầu tiên trên hệ thống của bạn (ổ có tên gần với
tên Partition cuối cùng của máy).
Binh khí sử dụng : 2 CommandButton
Đoạn mã :
Option Explicit
Private Declare Function mciSendString Lib "winmm.dll" Alias
"mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString
As String, ByVal uReturnLength As Long, ByVal hWndCallback As Long) As
Long
Function vbmciSendString(ByVal Command As String, ByVal hWnd As Long)
As String
Dim Buffer As String
Dim dwRet As Long
Buffer = Space$(100)
dwRet = mciSendString(Command, ByVal Buffer, Len(Buffer), hWnd)
vbmciSendString = Buffer
End Function
Private Sub Command1_Click()
Dim Dummy As String
Dummy = vbmciSendString("set cdaudio door open", 0)
End Sub
Private Sub Command2_Click()
Dim Dummy As String
Dummy = vbmciSendString("set cdaudio door closed ", 0)

End Sub

Đôc chiêu 13 : Tạo một SystemTray cho ứng dụng của bạn home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : Tương đối nhiều
Đoạn mã :

PHẦN I _ Tạo một OCX đặt tên là cSysTray.ocx

Bạn vào VB tạo một ActiveX Control, sau đó add một Module đặt tên là: mSysTray.bas và có nội
dung như sau :
--------- Module mSysTray.bas ----------

Option Explicit

Public Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal


lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal MSG As Long, ByVal wParam As Long,
ByVal lParam As Long) As Long
Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As
Long, ByVal nIndex As Long) As Long
Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As
Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal
dwMessage As Long, lpData As NOTIFYICONDATA) As Long
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (pDest As Any, pSource
As Any, ByVal ByteLen As Long)
Public Declare Function DrawEdge Lib "user32" (ByVal hDC As Long, qrc As RECT, ByVal edge
As Long, ByVal grfFlags As Long) As Boolean

Public Const GWL_USERDATA = (-21&)


Public Const GWL_WNDPROC = (-4&)
Public Const WM_USER = &H400&

Public Const TRAY_CALLBACK = (WM_USER + 101&)


Public Const NIM_ADD = &H0&
Public Const NIM_MODIFY = &H1&
Public Const NIM_DELETE = &H2&
Public Const NIF_MESSAGE = &H1&
Public Const NIF_ICON = &H2&
Public Const NIF_TIP = &H4&

Public Const WM_MOUSEMOVE = &H200&


Public Const WM_LBUTTONDOWN = &H201&
Public Const WM_LBUTTONUP = &H202&
Public Const WM_LBUTTONDBLCLK = &H203&
Public Const WM_RBUTTONDOWN = &H204&
Public Const WM_RBUTTONUP = &H205&
Public Const WM_RBUTTONDBLCLK = &H206&

Public Const BDR_RAISEDOUTER = &H1&


Public Const BDR_RAISEDINNER = &H4&
Public Const BF_LEFT = &H1&
Public Const BF_TOP = &H2&
Public Const BF_RIGHT = &H4&
Public Const BF_BOTTOM = &H8&
Public Const BF_RECT = BF_LEFT Or BF_TOP Or BF_RIGHT Or BF_BOTTOM
Public Const BF_SOFT = &H1000&

Public Type NOTIFYICONDATA


cbSize As Long
hwnd As Long
uID As Long
uFlags As Long
uCallbackMessage As Long
hIcon As Long
szTip As String * 64
End Type
Public Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type

Public PrevWndProc As Long


'------------------------------------------------------------
Public Function SubWndProc(ByVal hwnd As Long, ByVal MSG As Long, ByVal wParam As Long,
ByVal lParam As Long) As Long
'------------------------------------------------------------
Dim SysTray As cSysTray
Dim ClassAddr As Long
'------------------------------------------------------------
Select Case MSG
Case TRAY_CALLBACK
ClassAddr = GetWindowLong(hwnd, GWL_USERDATA)
CopyMemory SysTray, ClassAddr, 4

SysTray.SendEvent lParam, wParam

CopyMemory SysTray, 0&, 4


End Select

SubWndProc = CallWindowProc(PrevWndProc, hwnd, MSG, wParam, lParam)


'------------------------------------------------------------
End Function
'------------------------------------------------------------

--------- End mSysTray.bas -------------------

Sau khi bạn tạo module trên rồi, bạn tạo tiếp một cSysTray.ctl như sau:

----------------- cSysTray.ctl---------------------

Option Explicit
Private gInTray As Boolean
Private gTrayId As Long
Private gTrayTip As String
Private gTrayHwnd As Long
Private gTrayIcon As StdPicture
Private gAddedToTray As Boolean
Const MAX_SIZE = 510

Private Const defInTray = False


Private Const defTrayTip = "System Tray Control" & vbNullChar

Private Const sInTray = "InTray"


Private Const sTrayIcon = "TrayIcon"
Private Const sTrayTip = "TrayTip"

Public Event MouseMove(Id As Long)


Public Event MouseDown(Button As Integer, Id As Long)
Public Event MouseUp(Button As Integer, Id As Long)
Public Event MouseDblClick(Button As Integer, Id As Long)

'-------------------------------------------------------
Private Sub UserControl_Initialize()
'-------------------------------------------------------
gInTray = defInTray
gAddedToTray = False
gTrayId = 0
gTrayHwnd = hwnd
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub UserControl_InitProperties()
'-------------------------------------------------------
InTray = defInTray
TrayTip = defTrayTip
Set TrayIcon = Picture
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub UserControl_Paint()
'-------------------------------------------------------
Dim edge As RECT
'-------------------------------------------------------
edge.Left = 0
edge.Top = 0
edge.Bottom = ScaleHeight
edge.Right = ScaleWidth
DrawEdge hDC, edge, BDR_RAISEDOUTER, BF_RECT Or BF_SOFT
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
'-------------------------------------------------------
With PropBag
InTray = .ReadProperty(sInTray, defInTray)
Set TrayIcon = .ReadProperty(sTrayIcon, Picture)
TrayTip = .ReadProperty(sTrayTip, defTrayTip)
End With
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
'-------------------------------------------------------
With PropBag
.WriteProperty sInTray, gInTray
.WriteProperty sTrayIcon, gTrayIcon
.WriteProperty sTrayTip, gTrayTip
End With
'-------------------------------------------------------
End Sub
'-------------------------------------------------------
'-------------------------------------------------------
Private Sub UserControl_Resize()
'-------------------------------------------------------
Height = MAX_SIZE
Width = MAX_SIZE
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub UserControl_Terminate()
'-------------------------------------------------------
If InTray Then
InTray = False
End If
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Public Property Set TrayIcon(Icon As StdPicture)
'-------------------------------------------------------
Dim Tray As NOTIFYICONDATA
Dim rc As Long
'-------------------------------------------------------
If Not (Icon Is Nothing) Then
If (Icon.Type = vbPicTypeIcon) Then
If gAddedToTray Then
Tray.uID = gTrayId
Tray.hwnd = gTrayHwnd
Tray.hIcon = Icon.Handle
Tray.uFlags = NIF_ICON
Tray.cbSize = Len(Tray)

rc = Shell_NotifyIcon(NIM_MODIFY, Tray)
End If

Set gTrayIcon = Icon


Set Picture = Icon
PropertyChanged sTrayIcon
End If
End If
'-------------------------------------------------------
End Property
'-------------------------------------------------------

'-------------------------------------------------------
Public Property Get TrayIcon() As StdPicture
'-------------------------------------------------------
Set TrayIcon = gTrayIcon
'-------------------------------------------------------
End Property
'-------------------------------------------------------
'-------------------------------------------------------
Public Property Let TrayTip(Tip As String)
'-------------------------------------------------------
Dim Tray As NOTIFYICONDATA
Dim rc As Long
'-------------------------------------------------------
If gAddedToTray Then
Tray.uID = gTrayId
Tray.hwnd = gTrayHwnd
Tray.szTip = Tip & vbNullChar
Tray.uFlags = NIF_TIP
Tray.cbSize = Len(Tray)

rc = Shell_NotifyIcon(NIM_MODIFY, Tray)
End If

gTrayTip = Tip
PropertyChanged sTrayTip
'-------------------------------------------------------
End Property
'-------------------------------------------------------

'-------------------------------------------------------
Public Property Get TrayTip() As String
'-------------------------------------------------------
TrayTip = gTrayTip
'-------------------------------------------------------
End Property
'-------------------------------------------------------

'-------------------------------------------------------
Public Property Let InTray(Show As Boolean)
'-------------------------------------------------------
Dim ClassAddr As Long
'-------------------------------------------------------
If (Show <> gInTray) Then
If Show Then
If Ambient.UserMode Then
PrevWndProc = SetWindowLong(gTrayHwnd, GWL_WNDPROC, AddressOf SubWndProc)

SetWindowLong gTrayHwnd, GWL_USERDATA, ObjPtr(Me)

AddIcon gTrayHwnd, gTrayId, TrayTip, TrayIcon


gAddedToTray = True
End If
Else
If gAddedToTray Then
DeleteIcon gTrayHwnd, gTrayId

SetWindowLong gTrayHwnd, GWL_WNDPROC, PrevWndProc


gAddedToTray = False
End If
End If
gInTray = Show
PropertyChanged sInTray
End If
'-------------------------------------------------------
End Property
'-------------------------------------------------------

'-------------------------------------------------------
Public Property Get InTray() As Boolean
'-------------------------------------------------------
InTray = gInTray
'-------------------------------------------------------
End Property
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub AddIcon(hwnd As Long, Id As Long, Tip As String, Icon As StdPicture)
'-------------------------------------------------------
Dim Tray As NOTIFYICONDATA
Dim tFlags As Long
Dim rc As Long
'-------------------------------------------------------
Tray.uID = Id
Tray.hwnd = hwnd

If Not (Icon Is Nothing) Then


Tray.hIcon = Icon.Handle
Tray.uFlags = Tray.uFlags Or NIF_ICON
Set gTrayIcon = Icon
End If

If (Tip <> "") Then


Tray.szTip = Tip & vbNullChar
Tray.uFlags = Tray.uFlags Or NIF_TIP
gTrayTip = Tip
End If

Tray.uCallbackMessage = TRAY_CALLBACK
Tray.uFlags = Tray.uFlags Or NIF_MESSAGE
Tray.cbSize = Len(Tray)

rc = Shell_NotifyIcon(NIM_ADD, Tray)
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Private Sub DeleteIcon(hwnd As Long, Id As Long)
'-------------------------------------------------------
Dim Tray As NOTIFYICONDATA
Dim rc As Long
'-------------------------------------------------------
Tray.uID = Id
Tray.hwnd = hwnd
Tray.uFlags = 0&
Tray.cbSize = Len(Tray)

rc = Shell_NotifyIcon(NIM_DELETE, Tray)
'-------------------------------------------------------
End Sub
'-------------------------------------------------------

'-------------------------------------------------------
Friend Sub SendEvent(MouseEvent As Long, Id As Long)
'-------------------------------------------------------
Select Case MouseEvent
Case WM_MOUSEMOVE
RaiseEvent MouseMove(Id)
Case WM_LBUTTONDOWN
RaiseEvent MouseDown(vbLeftButton, Id)
Case WM_LBUTTONUP
RaiseEvent MouseUp(vbLeftButton, Id)
Case WM_LBUTTONDBLCLK
RaiseEvent MouseDblClick(vbLeftButton, Id)
Case WM_RBUTTONDOWN
RaiseEvent MouseDown(vbRightButton, Id)
Case WM_RBUTTONUP
RaiseEvent MouseUp(vbRightButton, Id)
Case WM_RBUTTONDBLCLK
RaiseEvent MouseDblClick(vbRightButton, Id)
End Select
'-------------------------------------------------------
End Sub
'-------------------------------------------------------
-----------------End cSysTray.ctl------------------------

Sau khi tạo xong hai phần trên, bạn biên dịch nó thành một Control OCX và đặt tên là
cSysTray.ocx... Vậy là bạn đã xong phần thứ nhất

PHẦN II: tạo một project mới để dùng OCX cSysTray.ocx


Bạn nhập đoạn mã sau vào :
Private Sub cSysTray1_MouseUp(Button As Integer, Id As Long)
'Nếu bạn nhấn chuột phải lên systray Icon
Select Case Button
Case vbRightButton
PopupMenu MainMenu
End Select
End Sub

Private Sub Form_Load()


Me.Visible=False
cSysTray1.InTray=True
cSysTray1.TrayTip="http://www.khunglongbeo.com/
End Sub

Đôc chiêu 14 : Thay đổi Font tiếng việt cho Menu của Window home
Xuất xứ : www.pcworld.com.vn
Binh khí sử dụng : Không
Đoạn mã :
'Các hằng được dùng cho các hàm API

Private Const LF_FaceSize=32

Private Type LOGFONT

lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharset As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(1 To LF_FaceSize) As Byte

End Type

Private Type NONCLIENTMETRICS

cbSize As Long
iBorderWidth As Long
iScrollWidth As Long
iScoolHeight As Long
iCaptionWidth As Long
iCaptionHeight As Long
iSMCaptionWidth As Long
iSMCaptionHeight As Long
lfCaptionFont As LOGFONT
iMenuWidth As Long
iMenuHeight As Long
lfMenuFont As LOGFONT
lfStatusFont As LOGFONT
lfMessageFont As LOGFONT

End Type

Const SPI_SetNonClientMetrics = 42
Const SPI_GettNonClientMetrics = 41

'Các hàm API cần thiết

'Hàm SystemParametersInfo sẽ gọi lại tất cả thông tin các tham số ngoài hệ thống. Nó còn có
khả năng cập nhật những thông tin do người dùng tự phát triển. Chính vì thế bạn dùng nó để
thay đổi Font là rất hợp lí
Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA"
(ByVal uAction As Long, Byval uParam As Long, ByRef lpvParam As Any, ByVal fuWinIni As
Long) As Long
Private Const REF_StructureSize = 340 ` Sizeof( NONCLIENTMETRICS)
Private Const VNI_FontHeight = -13
Private Const VNI_FontWeight = 700
Private Const VNI_FontName = "VNI-Palatin"
Private Const VNI_FontLen = 11 `Len(VNI_FontName)

Private FontMetric As NONCLIENTMETRICS


Private OldFontMetric As NONCLIENTMETRICS

'Thủ tục này dùng để thay đổi Font của Menu


Private Sub ChangeFont()

Dim I As Integer
Dim VarGT As Long
Dim VarHeight As Long
Dim VarWeight As Long
Dim VarStr As String

FontMetric.cbSize = REG_StructureSize

VarGT = SystemParametersInfo(SPI_GetNonClientMetrics,REG_StructureSize, FontMetric, 0)

OldFontMetric =FontMetric
FontMetric.lfCaptionFont.lfHeight = VNI_FontHeight
FontMetric.lfCaptionFont.lfWeight = VNI_FontWeight
VarStr = VNI_FontName
For I=1 To LF_FaceSize
If I <= VNI_FontLen Then
FontMetric.lfCaptionFont.lfFaceName(I)= CByte(Asc(Mid(VarStr,I,1)))
FontMetric.lfMenuFont.lfFaceName(I)= CByte(Asc(Mid(VarStr,I,1)))
Else
FontMetric.lfCaptionFont.lfFaceName(I) = 0
FontMetric.lfMenuFont.lfFaceName(I) = 0
End If
Next I
VarGT= SystemParametersInfo
(SPI_SetNonClientMetrics, REG_StructureSize, FontMetric,0)
End Sub

'THủ tục để phục hồi lại font cho menu


Private Sub RestoreFont()
Dim VarGT As Long
VarGT= SystemParametersInfo (SPI_SetNonClientMetrics, REG_StructureSize, OldFontMetric,0)
End Sub

'Khi form được khởi tạo thì đổi Font


Private Sub Form_Load()
ChangeFont
End Sub

'Khi form thoát thì khởi tạo lại font mặc định cho hệ thống bước này quan trọng vì nếu bạn không
phục hồi lại font hệ thống thì các menu khác trong Window sẽ nhảy lộn xộn cả lên
Private Sub Form_UnLoad(Cancel As Integer)
RestoreFont
End
End Sub

Đôc chiêu 14 : Hiện Icon đại diện cho một loại file home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : 1 Module
Đoạn mã :

'Bạn tạo một module mới và dán đoạn mã này vào

'Các hàm API cần thiết

Private Declare Function RegCreateKey Lib "advapi32.dll" _


Alias "RegCreateKeyA" (ByVal hKey As Long, _
ByVal lpSubKey As String, _
phkResult As Long) As Long

Private Declare Function RegSetValue Lib "advapi32.dll" _


Alias "RegSetValueA" (ByVal hKey As Long, _
ByVal lpSubKey As String, _
ByVal dwType As Long, _
ByVal lpData As String, _
ByVal cbData As Long) As Long

'Thực chất của việc tạo Icon riêng cho ứng dụng là việc bạn đăng kí cho Registry của Window
biết là bạn đã đăng nhập vào "quốc gia" của họ

'Các hằng số mang giá trị phản hồi từ Registry


Const ERROR_SUCCESS = 0&
Const ERROR_BADDB = 1&
Const ERROR_BADKEY = 2&
Const ERROR_CANTOPEN = 3&
Const ERROR_CANTREAD = 4&
Const ERROR_CANTWRITE = 5&
Const ERROR_OUTOFMEMORY = 6&
Const ERROR_INVALID_PARAMETER = 7&
Const ERROR_ACCESS_DENIED = 8&

Private Const HKEY_CLASSES_ROOT = &H80000000


Private Const MAX_PATH = 260&
Private Const REG_SZ = 1

'Hàm API cần thiết


Private Declare Sub SHChangeNotify Lib "shell32.dll" _
(ByVal wEventId As Long, _
ByVal uFlags As Long, _
dwItem1 As Any, _
dwItem2 As Any)

Const SHCNE_ASSOCCHANGED = &H8000000


Const SHCNF_IDLIST = &H0&

'THủ tục dùng để đăng kí Icon cho chương trình


Public Sub Tao_File_He_Thong()
'Giả sử rằng chương trình của bạn sẽ đăng kí ch việc thay đổi các tập tin có phần mở rộng là
"*.mp3".

Dim sKeyName As String 'Nắm tên khoá trong Reg


Dim sKeyValue As String ''Nắm một giá trị của khoá trong Reg

Dim Ret&
Dim lphKey&
Dim Path As String

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

'Đăng kí cho một giá trị khoá gốc là tên ứng dụng của bạn. Ví dụ, bạn đặt tên cho chương trình là
"Khunglongbeo.exe" thì giá trị của nó là "Khunglongbeo" và khi hoàn tất, tập tin sẽ có thuộc tính
là "Khunglongbeo's File " (một hàng chữ mờ mờ bên dưới các file mà bạn thương gặp)

sKeyName = "Khunglongbeo"
sKeyValue = "Khunglongbeo's File"
Ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)
Ret& = RegSetValue&(lphKey&, "", REG_SZ, sKeyValue, 0&)

'Đăng kí phần mở rộng "*.mp3" liên kết với ứng dụng mang tên "khunglongbeo" của bạn
sKeyName = ".mp3"
sKeyValue = "Khunglongbeo"
Ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)
Ret& = RegSetValue&(lphKey&, "", REG_SZ, sKeyValue, 0&)

sKeyName = "Khunglongbeo"
sKeyValue = Path & "Khunglongbeo.exe %1"
Ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)
Ret& = RegSetValue&(lphKey&, "shell\open\command", REG_SZ, _
sKeyValue, MAX_PATH)

'Lấy một Icon làm ảnh đại diện


sKeyName = "Khunglongbeo"
'Bạn hãy tìm một file .Ico bất kì và lưu vào đường dẫn sẽ qui định bên dưới (đường dẫn này tuỳ
bạn qui định)
sKeyValue = Path & "KLB.ico"
Ret& = RegCreateKey&(HKEY_CLASSES_ROOT, sKeyName, lphKey&)
Ret& = RegSetValue&(lphKey&, "DefaultIcon", REG_SZ, _
sKeyValue, MAX_PATH)

'Đổi Icon
SHChangeNotify SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0

End Sub

'**************************
'Phần mã này bạn hãy nhập vào Form1
Private Sub Form_Load()
Tao_File_He_Thong
End Sub

Đôc chiêu 15 : So sánh hai ảnh home


Xuất xứ : www.ttvnol.com
Binh khí sử dụng :

Bạn vẽ lên form1 các control sau :


2 picture box (picture1 và picture2)
2 label edit (label1 và label2)
1 command button (command1)
Bạn trang trí form như hình sau:

Đoạn mã :

''Mã nguồn so sánh hai hình ảnh có định dạng bất kì


Được viết bởi khunglongbeo
Email Address: khunglongbeo@hotmail.com
Ngày viết : 11/06/2003

‘ Do tôn trọng tác giả n ên tôi xin đ ược giữ nguyên phần này
''Cac ham API can thiet
Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal
X As Long, ByVal Y As Long) As Long
Private Declare Function SetPixel Lib "gdi32" (ByVal hdc As Long, ByVal
X As Long, ByVal Y As Long, ByVal crColor As Long) As Long
'----------------------------------------------------------------------
-----------
''Ham dung de so sanh xem hai hinh co giong nhau khong ? 
Private Sub So_Sanh(lpHinh1 As PictureBox, lpHinh2 As PictureBox)
Dim i As Long
Dim j As Long
Dim Mang1() As Long
Dim Mang2() As Long
Dim Co As Integer
''Chuyen tung anh sang che do pixels 
lpHinh1.ScaleMode = vbPixels
lpHinh2.ScaleMode = vbPixels
Co = 0
''Duyet gia tri cho tung pixel anh 
ReDim Mang1(lpHinh1.Width, lpHinh1.Height) As Long
For i = 0 To lpHinh1.Width ­ 1
    For j = 0 To lpHinh1.Height ­ 1
        ''Luu tung gia tri pixel vao trong Mang1 
        Mang1(i, j) = GetPixel(lpHinh1.hdc, i, j)
        ''Tao thanh truot gia dinh dang quet tung pixel 
        SetPixel lpHinh1.hdc, i, j, vbRed
        SetPixel lpHinh1.hdc, i ­ 1, j, Mang1(i, j)
        lpHinh1.Refresh
        ''Dinh vi tri pixel hien hanh 
        lbl1.Caption = "X : Y = " & i & ":" & j
        DoEvents
    Next j
Next i
''Doan ma nay giong ma tren dung de xu li anh 2 
ReDim Mang2(lpHinh2.Width, lpHinh2.Height) As Long
For i = 0 To lpHinh2.Width ­ 1
    For j = 0 To lpHinh2.Height ­ 1
        Mang2(i, j) = GetPixel(lpHinh2.hdc, i, j)
        SetPixel lpHinh2.hdc, i, j, vbRed
        SetPixel lpHinh2.hdc, i ­ 1, j, Mang2(i, j)
        lpHinh2.Refresh
        lbl2.Caption = "X : Y = " & i & ":" & j
        DoEvents
    Next j
Next i
''So sanh tung pixel tu hai mang trung gian
On Error Resume Next
If (lpHinh1.Width * lpHinh1.Height) >= (lpHinh2.Width * lpHinh2.Height) 
Then
    For i = 0 To lpHinh1.Width ­ 1
        For j = 0 To lpHinh1.Height ­ 1
            If Mang1(i, j) <> Mang2(i, j) Then
                Co = Co + 1
                MsgBox "The nay ma bao giong nhau a ???"
                Exit Sub
End If
Next j
Next i
If Co = 0 Then
MsgBox "Hai hinh nay giong y nhau ta oi !"
End If
Else
For i = 0 To lpHinh2.Width - 1
For j = 0 To lpHinh2.Height - 1
If Mang1(i, j) <> Mang2(i, j) Then
Co = Co + 1
MsgBox "The nay ma bao giong nhau a ???"
Exit Sub
End If
Next j
Next i
If Co = 0 Then
MsgBox "Hai hinh nay giong y nhau ta oi!"
End If
End If
End Sub
Private Sub CmdSS_Click()
Call So_Sanh(Pic1, Pic2)
End Sub
Private Sub Form_Load()
On Error Resume Next
'Doi voi picture1
Picture1.Name = "Pic1"
Picture1.AutoRedraw = True
Picture1.AutoSize = True
Picture1.Appearance = True
Picture1.BorderStyle = 0
''Doi voi picture2
    Picture2.Name = "Pic2"
    Picture2.AutoRedraw = True
    Picture2.AutoSize = True
    Picture2.Appearance = True
    Picture2.BorderStyle = 0
    ''Doi voi cac label
    Label1.Name = "lbl1"
    Label2.Name = "lbl2"
    ''Doi voi command button
    Command1.Name = "CmdSS"
    Command1.Font = "VNI­Palatin"
    Command1.Caption = "So sánh"
    ''Doi voi form 
    Me.AutoRedraw = True
    Me.ScaleMode = vbPixels
End Sub

Lời kết
Bạn chạy thử và xem điều gì sẽ xảy ra. Chương trình sẽ chạy rất chậm nếu như hình có kích
thước lớn. Tuy nhiên, kết quả cũng không tệ... Đối với những hình có độ nhoè, bạn có thể qui
định bằng cách thêm một số nguyên trong hàm để qui định phần trăm độ nhoè.... Kĩ thuật nhận
dạng giới hạn độ nhoè cho phép bảo mật bằng sinh trắc học thực ra cũng không khó về thuật
toán. Chỉ cần có máy móc kĩ thuật cao một tí là các bạn có thể làm mọi thứ mình cần

Đôc chiêu 16 : Liệt kê danh sách các thành phần phần cứng trong máy home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : Không
Đoạn mã :

Dim Ports(0 To 100) As PORT_INFO_2


Const KT_TYPE = 0
Const PRINTER_ENUM_LOCAL = &H2
Private Type PRINTER_INFO_1
flags As Long
pDescription As String
pName As String
pComment As String
End Type
Private Type DISPLAY_DEVICE
cb As Long
DeviceName As String * 32
DeviceString As String * 128
StateFlags As Long
DeviceID As String * 128
DeviceKey As String * 128
End Type
Private Declare Sub GetSystemInfo Lib "kernel32" (lpSystemInfo As
SYSTEM_INFO)
Private Type SYSTEM_INFO
dwOemID As Long
dwPageSize As Long
lpMinimumApplicationAddress As Long
lpMaximumApplicationAddress As Long
dwActiveProcessorMask As Long
dwNumberOrfProcessors As Long
dwProcessorType As Long
dwAllocationGranularity As Long
dwReserved As Long
End Type
Private Type PORT_INFO_2
pPortName As String
pMonitorName As String
pDescription As String
fPortType As Long
Reserved As Long
End Type
Private Type API_PORT_INFO_2
pPortName As Long
pMonitorName As Long
pDescription As Long
fPortType As Long
Reserved As Long
End Type
Const MAX_HOSTNAME_LEN = 132
Const MAX_DOMAIN_NAME_LEN = 132
Const MAX_SCOPE_ID_LEN = 260
Const MAX_ADAPTER_NAME_LENGTH = 260
Const MAX_ADAPTER_ADDRESS_LENGTH = 8
Const MAX_ADAPTER_DESCRIPTION_LENGTH = 132
Const ERROR_BUFFER_OVERFLOW = 111
Const MIB_IF_TYPE_ETHERNET = 1
Const MIB_IF_TYPE_TOKENRING = 2
Const MIB_IF_TYPE_FDDI = 3
Const MIB_IF_TYPE_PPP = 4
Const MIB_IF_TYPE_LOOPBACK = 5
Const MIB_IF_TYPE_SLIP = 6

Private Type IP_ADDR_STRING


Next As Long
IpAddress As String * 16
IpMask As String * 16
Context As Long
End Type

Private Type IP_ADAPTER_INFO


Next As Long
ComboIndex As Long
AdapterName As String * MAX_ADAPTER_NAME_LENGTH
Description As String * MAX_ADAPTER_DESCRIPTION_LENGTH
AddressLength As Long
Address(MAX_ADAPTER_ADDRESS_LENGTH - 1) As Byte
Index As Long
Type As Long
DhcpEnabled As Long
CurrentIpAddress As Long
IpAddressList As IP_ADDR_STRING
GatewayList As IP_ADDR_STRING
DhcpServer As IP_ADDR_STRING
HaveWins As Boolean
PrimaryWinsServer As IP_ADDR_STRING
SecondaryWinsServer As IP_ADDR_STRING
LeaseObtained As Long
LeaseExpires As Long
End Type

Private Type FIXED_INFO


HostName As String * MAX_HOSTNAME_LEN
DomainName As String * MAX_DOMAIN_NAME_LEN
CurrentDnsServer As Long
DnsServerList As IP_ADDR_STRING
NodeType As Long
ScopeId As String * MAX_SCOPE_ID_LEN
EnableRouting As Long
EnableProxy As Long
EnableDns As Long
End Type

Private Declare Function GetNetworkParams Lib "IPHlpApi" (FixedInfo As


Any, pOutBufLen As Long) As Long
Private Declare Function GetAdaptersInfo Lib "IPHlpApi" (IpAdapterInfo
As Any, pOutBufLen As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory"
(Destination As Any, Source As Any, ByVal Length As Long)

Private Declare Function EnumPorts Lib "winspool.drv" Alias


"EnumPortsA" (ByVal pName As String, ByVal Level As Long, ByVal
lpbPorts As Long, ByVal cbBuf As Long, pcbNeeded As Long, pcReturned As
Long) As Long
Private Declare Function lstrlenW Lib "kernel32" (ByVal lpString As
Long) As Long
Private Declare Sub CopyMem Lib "kernel32" Alias "RtlMoveMemory" (pTo
As Any, uFrom As Any, ByVal lSize As Long)
Private Declare Function HeapAlloc Lib "kernel32" (ByVal hHeap As Long,
ByVal dwFlags As Long, ByVal dwBytes As Long) As Long
Private Declare Function GetProcessHeap Lib "kernel32" () As Long
Private Declare Function HeapFree Lib "kernel32" (ByVal hHeap As Long,
ByVal dwFlags As Long, lpMem As Any) As Long

Private Declare Function EnumDisplayDevices Lib "user32" Alias


"EnumDisplayDevicesA" (Unused As Any, ByVal iDevNum As Long,
lpDisplayDevice As DISPLAY_DEVICE, ByVal dwFlags As Long) As Boolean
Private Declare Function EnumPrinters Lib "winspool.drv" Alias
"EnumPrintersA" (ByVal flags As Long, ByVal name As String, ByVal Level
As Long, pPrinterEnum As Long, ByVal cdBuf As Long, pcbNeeded As Long,
pcReturned As Long) As Long
Private Declare Function lstrcpy Lib "kernel32.dll" Alias "lstrcpyA"
(ByVal lpString1 As String, ByVal lpString2 As Long) As Long
Private Declare Function lstrlen Lib "kernel32.dll" Alias "lstrlenA"
(ByVal lpString As Long) As Long
Private Declare Function GetKeyboardType Lib "user32" (ByVal nTypeFlag
As Long) As Long
'*********************************************************************'
Liệt kê tên của Card Màn hình
Private Sub Ten_Card_ManHinh()
Dim DD As DISPLAY_DEVICE
DD.cb = Len(DD)
If EnumDisplayDevices(ByVal 0&, 0, DD, ByVal 0&) Then
Me.Print "Teân cuûa card maøn hình : " + Left$(DD.DeviceString,
InStr(1, DD.DeviceString, Chr$(0)) - 1)
Else
Me.Print "Khoâng thaáy card maøn hình"
End If
End Sub
'*********************************************************************'
LIệt kê danh sách tên máy in
Private Sub Ten_Cac_May_In()
Dim longbuffer() As Long
Dim printinfo() As PRINTER_INFO_1
Dim numbytes As Long
Dim numneeded As Long
Dim numprinters As Long
Dim c As Integer, retval As Long
numbytes = 3076
ReDim longbuffer(0 To numbytes / 4) As Long
retval = EnumPrinters(PRINTER_ENUM_LOCAL, "", 1, longbuffer(0),
numbytes, numneeded, numprinters)
If retval = 0 Then
numbytes = numneeded
ReDim longbuffer(0 To numbytes / 4) As Long
retval = EnumPrinters(PRINTER_ENUM_LOCAL, "", 1, longbuffer(0),
numbytes, numneeded, numprinters)
If retval = 0 Then
Debug.Print "Could not successfully enumerate the printes."
End
End If
End If
If numprinters <> 0 Then ReDim printinfo(0 To numprinters - 1) As
PRINTER_INFO_1
For c = 0 To numprinters - 1
printinfo(c).flags = longbuffer(4 * c)
printinfo(c).pDescription = Space(lstrlen(longbuffer(4 * c + 1)))
retval = lstrcpy(printinfo(c).pDescription, longbuffer(4 * c + 1))
printinfo(c).pName = Space(lstrlen(longbuffer(4 * c + 2)))
retval = lstrcpy(printinfo(c).pName, longbuffer(4 * c + 2))
printinfo(c).pComment = Space(lstrlen(longbuffer(4 * c + 3)))
retval = lstrcpy(printinfo(c).pComment, longbuffer(4 * c + 3))
Next c
For c = 0 To numprinters - 1
Me.Print "Teân cuûa maùy in thöù "; c + 1; " laø : "; printinfo(c).pName
Next c
End Sub
'*********************************************************************'
Hàm dùng để kiểu bàn phím
Private Sub Ban_Phim()
Select Case GetKeyboardType(KT_TYPE)
Case 1
Me.Print "Keyboard type: IBM PC/XT or compatible (83-key) keyboard"
Case 2
Me.Print "Keyboard type: Olivetti “ICO” (102-key) keyboard"
Case 3
Me.Print "Keyboard type: IBM PC/AT (84-key) or similar keyboard"
Case 4
Me.Print "Keyboard type: IBM enhanced (101- or 102-key) keyboard"
Case 5
Me.Print "Keyboard type: Nokia 1050 and similar keyboards"
Case 6
Me.Print "Keyboard type: Nokia 9140 and similar keyboards"
Case 7
Me.Print "Keyboard type: Japanese keyboard"
Case Else
Me.Print "Keyboard type: Unknown"
End Select
End Sub
'*********************************************************************
'Hàm lấy số serial và hiệu của CPU
Private Sub Lay_CPU()
Dim SInfo As SYSTEM_INFO
GetSystemInfo SInfo
Me.Print "soá löôïng CPU : " + Str$(SInfo.dwNumberOrfProcessors)
Me.Print "Ñôøi CPU : " + Str$(SInfo.dwProcessorType)
Me.Print "Ñòa chæ boä nhôù döôùi : " +
Str$(SInfo.lpMinimumApplicationAddress)
Me.Print "Ñòa chæ boä nhôù treân : " +
Str$(SInfo.lpMaximumApplicationAddress)
End Sub

'*********************************************************************'
Danh sách các Ports trong máy
Public Function TrimStr(strName As String) As String
Dim x As Integer
x = InStr(strName, vbNullChar)
If x > 0 Then TrimStr = Left(strName, x - 1) Else TrimStr = strName
End Function
Public Function LPSTRtoSTRING(ByVal lngPointer As Long) As String
Dim lngLength As Long
lngLength = lstrlenW(lngPointer) * 2
LPSTRtoSTRING = String(lngLength, 0)
CopyMem ByVal StrPtr(LPSTRtoSTRING), ByVal lngPointer, lngLength
LPSTRtoSTRING = TrimStr(StrConv(LPSTRtoSTRING, vbUnicode))
End Function
Public Function GetAvailablePorts(ServerName As String) As Long
Dim ret As Long
Dim PortsStruct(0 To 100) As API_PORT_INFO_2
Dim pcbNeeded As Long
Dim pcReturned As Long
Dim TempBuff As Long
Dim i As Integer
ret = EnumPorts(ServerName, 2, TempBuff, 0, pcbNeeded, pcReturned)
TempBuff = HeapAlloc(GetProcessHeap(), 0, pcbNeeded)
ret = EnumPorts(ServerName, 2, TempBuff, pcbNeeded, pcbNeeded,
pcReturned)
If ret Then
CopyMem PortsStruct(0), ByVal TempBuff, pcbNeeded
For i = 0 To pcReturned - 1
Ports(i).pDescription = LPSTRtoSTRING(PortsStruct(i).pDescription)
Ports(i).pPortName = LPSTRtoSTRING(PortsStruct(i).pPortName)
Ports(i).pMonitorName = LPSTRtoSTRING(PortsStruct(i).pMonitorName)
Ports(i).fPortType = PortsStruct(i).fPortType
Next
End If
GetAvailablePorts = pcReturned
If TempBuff Then HeapFree GetProcessHeap(), 0, TempBuff
End Function
Private Sub Lay_Ports()
Dim NumPorts As Long
Dim i As Integer
NumPorts = GetAvailablePorts("")
Me.Print "Daùnh saùch caùc Port hieän taïi"
For i = 0 To NumPorts - 1
Me.Print Ports(i).pPortName
Next
End Sub
'*********************************************************************'
Thôngt tin về tình trạng mạng và thông số card mạng
Private Sub Lay_Adepter()
Dim error As Long
Dim FixedInfoSize As Long
Dim AdapterInfoSize As Long
Dim i As Integer
Dim PhysicalAddress As String
Dim NewTime As Date
Dim AdapterInfo As IP_ADAPTER_INFO
Dim Adapt As IP_ADAPTER_INFO
Dim AddrStr As IP_ADDR_STRING
Dim FixedInfo As FIXED_INFO
Dim Buffer As IP_ADDR_STRING
Dim pAddrStr As Long
Dim pAdapt As Long
Dim Buffer2 As IP_ADAPTER_INFO
Dim FixedInfoBuffer() As Byte
Dim AdapterInfoBuffer() As Byte

FixedInfoSize = 0
error = GetNetworkParams(ByVal 0&, FixedInfoSize)
If error <> 0 Then
If error <> ERROR_BUFFER_OVERFLOW Then
Me.Print "GetNetworkParams sizing failed with error " & error
Exit Sub
End If
End If
ReDim FixedInfoBuffer(FixedInfoSize - 1)

error = GetNetworkParams(FixedInfoBuffer(0), FixedInfoSize)


If error = 0 Then
CopyMemory FixedInfo, FixedInfoBuffer(0), Len(FixedInfo)
Me.Print "Host Name: " & FixedInfo.HostName 'host name
Me.Print "DNS Servers: " & FixedInfo.DnsServerList.IpAddress 'dns
server IP
pAddrStr = FixedInfo.DnsServerList.Next
Do While pAddrStr <> 0
CopyMemory Buffer, ByVal pAddrStr, Len(Buffer)
Me.Print "DNS Servers: " & Buffer.IpAddress 'dns server IP
pAddrStr = Buffer.Next
Loop

Select Case FixedInfo.NodeType 'node type


Case 1
Me.Print "Node type: Broadcast"
Case 2
Me.Print "Node type: Peer to peer"
Case 4
Me.Print "Node type: Mixed"
Case 8
Me.Print "Node type: Hybrid"
Case Else
Me.Print "Unknown node type"
End Select

Me.Print "NetBIOS Scope ID: " & FixedInfo.ScopeId 'scope ID


'routing
If FixedInfo.EnableRouting Then
Me.Print "IP Routing Enabled "
Else
Me.Print "IP Routing not enabled"
End If
' proxy
If FixedInfo.EnableProxy Then
Me.Print "WINS Proxy Enabled "
Else
Me.Print "WINS Proxy not Enabled "
End If
' netbios
If FixedInfo.EnableDns Then
Me.Print "NetBIOS Resolution Uses DNS "
Else
Me.Print "NetBIOS Resolution Does not use DNS "
End If
Else
Me.Print "GetNetworkParams failed with error " & error
Exit Sub
End If

AdapterInfoSize = 0
error = GetAdaptersInfo(ByVal 0&, AdapterInfoSize)
If error <> 0 Then
If error <> ERROR_BUFFER_OVERFLOW Then
Me.Print "GetAdaptersInfo sizing failed with error " & error
Exit Sub
End If
End If
ReDim AdapterInfoBuffer(AdapterInfoSize - 1)

error = GetAdaptersInfo(AdapterInfoBuffer(0), AdapterInfoSize)


If error <> 0 Then
Me.Print "GetAdaptersInfo failed with error " & error
Exit Sub
End If
CopyMemory AdapterInfo, AdapterInfoBuffer(0), Len(AdapterInfo)
pAdapt = AdapterInfo.Next

Do While pAdapt <> 0


CopyMemory Buffer2, AdapterInfo, Len(Buffer2)
Select Case Buffer2.Type
Case MIB_IF_TYPE_ETHERNET
Me.Print "Ethernet adapter "
Case MIB_IF_TYPE_TOKENRING
Me.Print "Token Ring adapter "
Case MIB_IF_TYPE_FDDI
Me.Print "FDDI adapter "
Case MIB_IF_TYPE_PPP
Me.Print "PPP adapter"
Case MIB_IF_TYPE_LOOPBACK
Me.Print "Loopback adapter "
Case MIB_IF_TYPE_SLIP
Me.Print "Slip adapter "
Case Else
Me.Print "Other adapter "
End Select
Me.Print " AdapterName: " & Buffer2.AdapterName
Me.Print "AdapterDescription: " & Buffer2.Description 'adatpter name
For i = 0 To Buffer2.AddressLength - 1
PhysicalAddress = PhysicalAddress & Hex(Buffer2.Address(i))
If i < Buffer2.AddressLength - 1 Then
PhysicalAddress = PhysicalAddress & "-"
End If

Next
Me.Print "Physical Address: " & PhysicalAddress 'mac address
If Buffer2.DhcpEnabled Then
Me.Print "DHCP Enabled "
Else
Me.Print "DHCP disabled"
End If

pAddrStr = Buffer2.IpAddressList.Next
Do While pAddrStr <> 0
CopyMemory Buffer, Buffer2.IpAddressList, LenB(Buffer)
Me.Print "IP Address: " & Buffer.IpAddress
Me.Print "Subnet Mask: " & Buffer.IpMask
pAddrStr = Buffer.Next
If pAddrStr <> 0 Then
CopyMemory Buffer2.IpAddressList, ByVal pAddrStr,
Len(Buffer2.IpAddressList)
End If
Loop
Me.Print "Default Gateway: " & Buffer2.GatewayList.IpAddress
pAddrStr = Buffer2.GatewayList.Next
Do While pAddrStr <> 0
CopyMemory Buffer, Buffer2.GatewayList, Len(Buffer)
Me.Print "IP Address: " & Buffer.IpAddress
pAddrStr = Buffer.Next
If pAddrStr <> 0 Then
CopyMemory Buffer2.GatewayList, ByVal pAddrStr, Len(Buffer2.GatewayList)
End If
Loop

Me.Print "DHCP Server: " & Buffer2.DhcpServer.IpAddress


Me.Print "Primary WINS Server: " & Buffer2.PrimaryWinsServer.IpAddress
Me.Print "Secondary WINS Server: " &
Buffer2.SecondaryWinsServer.IpAddress

NewTime = CDate(Adapt.LeaseObtained)
Me.Print "Lease Obtained: " & CStr(NewTime)

NewTime = CDate(Adapt.LeaseExpires)
Me.Print "Lease Expires : " & CStr(NewTime)
pAdapt = Buffer2.Next
If pAdapt <> 0 Then
CopyMemory AdapterInfo, ByVal pAdapt, Len(AdapterInfo)
End If

Loop
End Sub
Private Sub Form_Load()
Me.Font = "VNI-Palatin"
Me.AutoRedraw = True
Ten_Card_ManHinh
Ten_Cac_May_In
Ban_Phim
Lay_CPU
Lay_Ports
Lay_Adepter
End Sub

Đôc chiêu 17 : Chương trình khởi động cùng với Windowns home
Xuất xứ : www.pscode.com
Binh khí sử dụng : Một Module
Đoạn mã :
Module :
Option Explicit
Public Const HKEY_CLASSES_ROOT = &H80000000
Public Const HKEY_LOCAL_MACHINE = &H80000002
Public Const ERROR_SUCCESS = 0&
Public Const HKEY_CURRENT_USER = &H80000001

Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As


Long

Declare Function RegCreateKey Lib "advapi32.dll" Alias "RegCreateKeyA"


(ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As
Long

Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA"


(ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As
Long

Declare Function RegQueryValueEx Lib "advapi32.dll" Alias


"RegQueryValueExA" (ByVal hKey As Long, ByVal lpValueName As String,
ByVal lpReserved As Long, lpType As Long, lpData As Any, lpcbData As
Long) As Long
Declare Function RegSetValueEx Lib "advapi32.dll" Alias
"RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String,
ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, ByVal
cbData As Long) As Long
Public Const REG_SZ = 1 ' Unicode nul terminated String

Public Function ReplaceChars(ByVal Text As String, ByVal Char As


String, ReplaceChar As String) As String
Dim counter As Integer

counter = 1
Do
counter = InStr(counter, Text, Char)
If counter <> 0 Then
Mid(Text, counter, Len(ReplaceChar)) = ReplaceChar
Else
ReplaceChars = Text
Exit Do
End If
Loop

ReplaceChars = Text
End Function

Public Function GetString(hKey As Long, strPath As String, strValue As


String, DefaultStr As Long) As String
'EXAMPLE:
'
'text1.text = getstring(HKEY_CURRENT_USE
' R, "Software\VBW\Registry", "String")
'
Dim keyhand As Long
Dim lResult As Long
Dim strBuf As String
Dim lDataBufSize As Long
Dim intZeroPos As Integer
Dim lValueType As Long
RegOpenKey hKey, strPath, keyhand
lResult = RegQueryValueEx(keyhand, strValue, 0&, lValueType, ByVal
0&, lDataBufSize)

If lValueType = REG_SZ Then


strBuf = String(lDataBufSize, " ")
lResult = RegQueryValueEx(keyhand, strValue, 0&, 0&, ByVal
strBuf, lDataBufSize)

If lResult = ERROR_SUCCESS Then


intZeroPos = InStr(strBuf, Chr$(0))

If intZeroPos > 0 Then


GetString = Left$(strBuf, intZeroPos - 1)
Else
GetString = strBuf
End If
End If
End If
If strBuf = "" Then GetString = DefaultStr
End Function
Public Sub SaveString(hKey As Long, strPath As String, strValue As
String, strdata As String)

Dim keyhand As Long


keyhand = 0
RegOpenKey hKey, strPath, keyhand
If keyhand = 0 Then RegCreateKey hKey, strPath, keyhand
RegSetValueEx keyhand, strValue, 0, REG_SZ, ByVal strdata,
Len(strdata)
RegCloseKey keyhand
End Sub
Form :
Function Khoidong()
If GetSetting("dungcoi", "dung", "Path") <> App.Path & "\" &
App.EXEName & ".exe" Then
SaveString HKEY_CLASSES_ROOT, "Folder\shell\Khoi dong Virus\command",
"", App.Path & "\" & App.EXEName & ".exe" & " /ADDDRV %1"
SaveString HKEY_CURRENT_USER,
"Software\Microsoft\Windows\CurrentVersion\Run", "dungcoi", App.Path &
"\" & App.EXEName & ".exe" & " /STARTUP"
SaveSetting "dungcoi", "dung", "Path", App.Path & "\" & App.EXEName &
".exe"
End If
End Function

Private Sub Form_Load()


Khoidong
End Sub
Đôc chiêu 18 : Play một file nhạc Midi home
Xuất xứ : Lê Nguyên Dũng (dungcoi2005) sửa lại từ www.allapi.net
Binh khí sử dụng : Một Module, 2 nút ấn (CommandButton)
Đoạn mã :
Module :
Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA"
(ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal
uReturnLength As Long, ByVal hwndCallback As Long) As Long
Form :

Private Sub Form_Load()


Command1.Caption = "Play"
Command2.Caption = "Stop"
End Sub
Private Sub Command1_Click()
result = mciSendString("open d:\Nhac.mid type sequencer alias
canyon", 0&, 0, 0)
result = mciSendString("play canyon", 0&, 0, 0)
End Sub

Private Sub Command2_Click()


result = mciSendString("close all", 0&, 0, 0)
End Sub
Đôc chiêu 19 : Khoá một file ảnh định dạng .bmp home
Xuất xứ : Lê Nguyên Dũng (dungcoi2005) sửa lại từ www.pscode.com
Binh khí sử dụng : 2 nút ấn (CommandButton)
Nói qua : Chiêu này rất hay các bạn ạ nó giúp bạn không cho người khác xem những tấm ảnh
bạn muốn và quan trọng hơn bạn có thể dễ dành viết một phần mềm bảo mật ảnh.
Đoạn mã :
Function MoKhoa(File)
A = FreeFile
Open File For Binary As #A
B$ = Chr(0)
Put #A, 17, B$
Close #A
End Function
Function KhoaAnh(File)
A = FreeFile
Open File For Binary As #A
B$ = "X"
Put #A, 17, B$
Close #A
End Function
Private Sub Command1_Click()
KhoaAnh ("d:\hinh anh.bmp")
End Sub
Private Sub Command2_Click()
MoKhoa ("d:\hinh anh.bmp")
End Sub
Private Sub Form_Load()
Command1.Caption = " Khoa file anh"
Command2.Caption = " Mo khoa file anh"
End Sub
Đôc chiêu 20 : Để form của bạn ở chế độ “Luôn nổi” home
Xuất xứ : Lê Nguyên Dũng (dungcoi2005) sửa lại từ www.allapi.net
Binh khí sử dụng : 1 Timer có giá trị Interval = 50 hoặc gì gì đó nhưng đừng lớn quá chương trình
kém “Nhạy” đừng nhỏ quá chương trình “Giật giật”
Đoạn mã :
Const HWND_TOPMOST = -1
Const HWND_NOTOPMOST = -2
Const SWP_NOSIZE = &H1
Const SWP_NOMOVE = &H2
Const SWP_NOACTIVATE = &H10
Const SWP_SHOWWINDOW = &H40
Private Declare Sub SetWindowPos Lib "User32" (ByVal hWnd As Long,
ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal
cx As Long, ByVal cy As Long, ByVal wFlags As Long)
Private Sub Timer1_Timer()
SetWindowPos Me.hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE Or
SWP_SHOWWINDOW Or SWP_NOMOVE Or SWP_NOSIZE
End Sub
Đôc chiêu 21 : TextBox chỉ “Chịu” nhận số home
Xuất xứ : www.allapi.net
Binh khí sử dụng : 1 TextBox và 1 Module
Đoạn mã :
Module
Const Number$ = "0123456789." ' Chỉ nhận các ký tự này
Form :
Private Sub Text1_KeyPress(KeyAscii As Integer)
If IsNumeric(Chr(KeyAscii)) <> True Then KeyAscii = 0
End Sub
Đôc chiêu 22 : Để form trở nên trong suốt home
Xuất xứ : www.allapi.net
Binh khí sử dụng : Không
Đoạn mã :
Const LWA_COLORKEY = &H1
Const LWA_ALPHA = &H2
Const GWL_EXSTYLE = (-20)
Const WS_EX_LAYERED = &H80000
Private Declare Function GetWindowLong Lib "user32" Alias
"GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias
"SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal
dwNewLong As Long) As Long
Private Declare Function SetLayeredWindowAttributes Lib "user32" (ByVal
hWnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, ByVal dwFlags
As Long) As Long
Private Sub Form_Load()
Dim Ret As Long
Ret = GetWindowLong(Me.hWnd, GWL_EXSTYLE)
Ret = Ret Or WS_EX_LAYERED
SetWindowLong Me.hWnd, GWL_EXSTYLE, Ret
SetLayeredWindowAttributes Me.hWnd, 0, 128, LWA_ALPHA
End Sub
‘ Chú ý số 128 : Chính là số chỉ định độ trong suốt (Số này từ 0->255)
Đôc chiêu 23 : Lấy tên người sử dung của Windowns home
Xuất xứ : www.allapi.net
Binh khí sử dụng : 1 Module
Đoạn mã :
Module :
Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA"
(ByVal lpBuffer As String, nSize As Long) As Long
Form :
Sub Get_User_Name()
Dim lpBuff As String * 25
Dim ret As Long, UserName As String
ret = GetUserName(lpBuff, 25)
UserName = Left(lpBuff, InStr(lpBuff, Chr(0)) - 1)
MsgBox UserName
End Sub
Private Sub Form_Load()
Get_User_Name
End Sub
Đôc chiêu 24 : Chép cả màn hình làm việc vào một Picture home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : 1 Picture và một nút ấn
Đoạn mã :
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function StretchBlt Lib "gdi32" (ByVal hdc As Long,
ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight
As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long,
ByVal nSrcWidth As Long, ByVal nSrcHeight As Long, ByVal dwRop As Long)
As Long
Private Sub Command1_Click()
Dim wScreen As Long
Dim hScreen As Long
Dim w As Long
Dim h As Long
Picture1.Cls
wScreen = Screen.Width \ Screen.TwipsPerPixelX
hScreen = Screen.Height \ Screen.TwipsPerPixelY
Picture1.ScaleMode = vbPixels
w = Picture1.ScaleWidth
h = Picture1.ScaleHeight

hdcScreen = GetDC(0)
r = StretchBlt(Picture1.hdc, 0, 0, w, h, hdcScreen, 0, 0, wScreen,
hScreen, vbSrcCopy)
End Sub
Đôc chiêu 25 : Dấu dữ liệu dạng text vào 1 file bất kỳ home
Xuất xứ : www.ttvnol.com
Binh khí sử dụng : Hai textbox đặt tên lần lượt là txtPath và txtContains. Hai command button đặt
tên lần lượt là CmdEncrypt và CmdDecrypt
Đoạn mã : (Khi Runtime nhớ nhập đường dẫn và nội dung)
Public Function Dat_Thong_Diep(DuongDan As String, ThongDiep As String)
As String
Open DuongDan For Binary As #1
Dim BoDem As String
BoDem = Space(LOF(1))
Get #1, , BoDem
Close #1
Dim Message As String
Open DuongDan For Binary As #2
Message = BoDem & ThongDiep & Chr(Len(ThongDiep))
Put #2, , Message
End Function
Public Function Lay_Thong_Diep(DuongDan As String) As String
Open DuongDan For Binary As #1
Dim BoDem As String
BoDem = Space(LOF(1))
Get #1, , BoDem
Close #1
Dim Message As String
Dim LuuC As String
LuuC = Right(BoDem, 1)
Message = Right(BoDem, Asc(LuuC) + 1)
Message = Left(Message, Len(Message) - 1)
Lay_Thong_Diep = Message
End Function

Private Sub CmdEncrypt_Click()


If txtPath <> "" And txtContains <> "" Then
Dat_Thong_Diep Trim$(txtPath), Trim$(txtContains)
End If
End Sub

Private Sub CmdDecrypt_Click()


txtContains = ""
If txtPath <> "" Then
txtContains = Lay_Thong_Diep(Trim$(txtPath))
End If
End Sub
Đôc chiêu 26 : Mở từng hộp thoại trong Control Panel home
Xuất xứ : www.pscode.com
Binh khí sử dụng : Không
Đoạn mã : ( Do có nhiều phần nên tôi chỉ đưa ra Code cơ bản)
'Hộp thoại System Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL sysdm.cpl
@1", 5)
‘Hộp thoại Add/Remove Programs
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL
appwiz.cpl,,1", 5)
' Hộp thoại Date/Time Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL
timedate.cpl", 5)
' Hộp thoại Display Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL
desk.cpl,,0", 5)
' Hộp thoại Game Controllers
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL joy.cpl", 5)
' Hộp thoại Internet Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL
inetcpl.cpl,,0", 5)
' Hộp thoại Keyboard Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL main.cpl
@1", 5)
' Hộp thoại Modem Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL modem.cpl",
5)
' Hộp thoại Mouse Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL main.cpl
@0", 5)
' Hộp thoại Multimedia Properties
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL
mmsys.cpl,,0", 5)
' Hộp thoại Network
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL netcpl.cpl",
5)
' Hộp thoại Regional Settings
Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL
intl.cpl,,0", 5)
' Hộp thoại Sounds Properties Dim dblReturn As Double
dblReturn = Shell("rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl
@1", 5)
Đôc chiêu 27 : Mã hoá dữ liệu dạng text home
Nói qua : Phần này rất hay các bạn nên chú ý trong thực tế ứng dụng nên sử dụng một file trung
gian để chứa dữ liệu được mã hoá
Xuất xứ : www.vbcode.com
Đây là Demo của tôi nè, rất ấn tượng phải không ai muốn có Source cứ mail cho tôi
Binh khí sử dụng : 2 Nút ấn với tên lần lượt là cmdEncode và cmdDecode, 3 TextBox với tên lần
lượt là txtDulieu , txtKetQua và txtGiaiMa (Đ ể test thì vậy là đủ còn tôi tất nhiên phải “Màu mè”
hơn rồi)
Đoạn mã :
Public Function Encode(Data As String, Optional Depth As Integer) As
String
Dim TempChar As String
Dim TempAsc As Integer
Dim NewData As String
Dim vChar As Integer

For vChar = 1 To Len(Data)


TempChar = Mid$(Data, vChar, 1)
TempAsc = Asc(TempChar)
If Depth = 0 Then Depth = 40
If Depth > 254 Then Depth = 254

TempAsc = TempAsc + Depth


If TempAsc > 255 Then TempAsc = TempAsc - 255
TempChar = Chr(TempAsc)
NewData = NewData & TempChar
Next vChar
Encode = NewData

End Function
Public Function Decode(Data As String, Optional Depth As Integer) As
String
Dim TempChar As String
Dim TempAsc As Integer
Dim NewData As String
Dim vChar As Integer

For vChar = 1 To Len(Data)


TempChar = Mid$(Data, vChar, 1)
TempAsc = Asc(TempChar)
If Depth = 0 Then Depth = 40
If Depth > 254 Then Depth = 254
TempAsc = TempAsc - Depth
If TempAsc < 0 Then TempAsc = TempAsc + 255
TempChar = Chr(TempAsc)
NewData = NewData & TempChar
Next vChar
Decode = NewData

End Function
Private Sub CmdEncode_Click()
TxtKetqua.Text = Encode(txtDulieu.Text, 9)
End Sub
Private Sub cmdDecode_Click()
txtGiaiMa.Text = Decode(TxtKetqua.Text, 9)
End Sub
‘ Chú ý : Ở chỗ số 9 chính là số ta cần để lựa chọn kiểu Mã hoá hay
Giải mã

Lời kết : Chao ôi mệt quá qua 1 buổi lối ngày 10 tháng 11 và cả một ngày 11 tháng 11 đã hoàn
thành 14 Chiêu thức, hình như hơi chậm thì phải các bạn, do phải “Lục tung” hết cái máy lên
mới tìm thấy những chiêu “Tâm đắt” để viết sách, nhất là chiêu Mã hoá dữ liệu dạng text đã làm
mình mất hơn 1 buổi tối mới tìm ra, kiểu này thì phải nhờ các bạn nếu có Chiêu thức nào hay thì
gửi Email cho mình để tổng hợp và nâng cấp cho cuốn sách lần sau (An tâm đi mình sẽ ghi
nhận các bạn trong cuốn sách từ trang bìa đến xuất xứ của chiêu thức đó), một mình làm chán
quá các bạn ạ. Mà mình cũng hết Chiêu thức để viết tiếp rồi. Chiêu thức lập trình phiên bản 2 tới
đây là hết mong các bạn đóng góp ý kiến để phiên bản sau hoàn thiện hơn

Lê Nguyên Dũng lớp 11C1 trường THPT Đăk Nông ( Thị xã Gia Nghĩa tỉnh Đăk Nông)
Ngày “Xuất bản” : 10h sáng ngày 12 tháng 11 năm 2005

You might also like