在撰寫 Vbscript 時,如果發現需要呼叫 Win32 API,或者使用 Vbscript 沒有提供的函數功能,可以透

過呼叫 Activex DLL 來達到自已的目的,以下利用 VB 6.0 來撰寫所需要的 Activex DLL,因 VB6.0

直接撰寫 Activex DLL 比使用其他語言撰寫 Activex DLL 簡單多了,不須太多額外步驟簡單好用。

 

新增 ActiveX DLL Project

image

 

把 Project 改成 System,Class Modules 改成 API (這邊大家自行定義即可)

image

 

撰寫 Class Modules 程式碼 (程式碼內容是之前要寫類似按鍵精靈的功能時撰寫的,這邊大家可以依照自己想要撰寫的程式碼撰寫)

Private Declare Function SendMsg Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function FindWin Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetCPos Lib "user32" Alias "GetCursorPos" (lpPoint As POINTAPI) As Long
Private Declare Function SetCPos Lib "user32" Alias "SetCursorPos" (ByVal x As Long, ByVal y As Long) As Long
Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Private Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
 
 
Public Type POINTAPI
    x As Long
    y As Long
End Type
 
Public Function SendMessage(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Variant) As Long
    SendMessage = SendMsg(hwnd, wMsg, wParam, lParam)
End Function
 
Public Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String)
    FindWindow = FindWin(lpClassName, lpWindowName)
End Function
 
Public Function GetCursorPos(ByRef x, ByRef y)
    Dim pos As POINTAPI
    Dim result
    result = GetCPos(pos)
    x = pos.x
    y = pos.y
    GetCursorPos = result
End Function
 
Public Function SetCursorPos(ByVal x As Long, ByVal y As Long)
    SetCursorPos = SetCPos(x, y)
End Function
 
Public Sub MouseEvent(ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long)
    mouse_event dwFlags, dx, dy, vbNull, vbNull
End Sub
 
Public Sub KeybdEvent(ByVal bVk As Byte, ByVal dwFlags As Long)
    keybd_event bVk, vbNull, dwFlags, vbNull
End Sub
 
Public Function Exec(ByVal path As String) As Double
    Exec = Shell(path, vbNormalNoFocus)
End Function
 

 

產生 DLL 檔案

image

 

Register DLL,在【開始】->【執行】鍵入 regsvr32 c:\system.dll (DLL 檔案路徑請按照你實際的情況,要 UnRegister DLL 鍵入 regsvr32 -u c:\system.dll  即可)

image

 

調用撰寫好的 ActiveX DLL,以下 Vbscript 程式動作為 ( 開啟 notepad,5 秒後自動關閉 )

rem 開啟 notepad,5 秒後自動關閉
 
Const WM_CLOSE = &H10
 
Set obj=CreateObject("System.API")
obj.Exec("c:\windows\notepad.exe")
hwnd=obj.FindWindow("notepad",vbNullString)
Wscript.sleep 5000
Call obj.SendMessage(hwnd,WM_CLOSE,0,0)
arrow
arrow
    全站熱搜

    iammic 發表在 痞客邦 留言(0) 人氣()