题前:
QTP调用DLL(Extern.Declare函数参数介绍)
QTP拥有自己的.NET Factory接口,以调用.NET生成的DLL,也可以使用Extern.Declare来进行外部的DLL的访问。
语法:
Extern.Declare(RetType, MethodName, LibName, Alias [, ArgType(s)])
参数说明:
RetType: 方法返回值的类型。
MethodName:调用DLL文件中的某个方法的方法名。
LibName: DLL文件名。
Alias: 别名,当别名为空时,方法名和别名一样(此参数通常为空)。
ArgType(s): 传入的参数。
例子:
Extern.Declare micHwnd, "FindWindow", "user32.dll", "FindWindowA", micString, micString '后面两个micString为函数FindWindow函数的参数
Extern.Declare micLong, "SetWindowText", "user32.dll", "SetWindowTextA", micHwnd, micString
例1:运行一个 可执行文件文件
Extern.Declare micLong, "WinExec", "kernel32.dll", "WinExec", micString,micLong
Extern.WinExec "d:/1.exe ", 1
例2:Beep
Extern.Declare micLong, "Beep", "kernel32.dll", "Beep", micLong
Extern.Beep 500
'它让我的机器在办公室里狂响不止!(不停的响暂不知如何中止,最好在虚拟机中试)
例3:QTP运行后锁键盘和鼠标。
Extern.Declare micLong, "BlockInput", "user32.dll", "BlockInput", micLong
' Use the following statement to lock keyboard and mouse input at the
Extern.BlockInput 1 ' beginning of the test:
wait(5)
' Use the following statement to unlock keyboard and mouse input at the
Extern.BlockInput 0 ' end of the test:
以下示例使用 Extern.Declare 和 Extern.<已声明的方法> 方法更改记事本窗口的标题。
'声明 FindWindow 方法
Extern.Declare micHwnd, "FindWindow", "user32.dll", "FindWindowA", micString, micString
'声明 SetWindowText 方法
Extern.Declare micLong, "SetWindowText", "user32.dll", "SetWindowTextA", micHwnd, micString
'获取记事本窗口的 HWND
hwnd = Extern.FindWindow("Notepad", vbNullString)
if hwnd = 0 then
MsgBox "找不到记事本窗口"
end if
'更改记事本窗口的标题
res = Extern.SetWindowText(hwnd, "hukai")
以下示例使用 GetPrivateProfileString 从外部 INI 文件中检索信息,并将该信息用于测试。注意,如果使用 micByRef 标志,则表示为输出参数。
Extern.Declare micInteger,"GetPrivateProfileStringA", "kernel32.dll","GetPrivateProfileStringA", micString, micString, micString, micString+micByRef, micInteger, micString
Dim key, i, key2
key = String(32, "-")
i = Extern.GetPrivateProfileStringA("WREnv","addons","xxx", key, 32, "wrun.ini")
key2 = Left(key,i)
msgbox key & ";" & key2 & ";" & CStr(i)
以下示例检查光标何时显示为沙漏。
extern.Declare micLong,"GetForegroundWindow","user32.dll","GetForegroundWindow"
extern.Declare micLong,"AttachThreadInput","user32.dll","AttachThreadInput",micLong,
micLong,micLong
extern.Declare micLong,"GetWindowThreadProcessId","user32.dll",
"GetWindowThreadProcessId",micLong,micLong
extern.Declare micLong,"GetCurrentThreadId","kernel32.dll","GetCurrentThreadId"
extern.Declare micLong,"GetCursor","user32.dll","GetCursor"
function get_cursor()
hwnd = extern.GetForegroundWindow()
pid = extern.GetWindowThreadProcessId(hWnd, NULL)
thread_id=extern.GetCurrentThreadId()
extern.AttachThreadInput pid,thread_id,True
get_cursor=extern.GetCursor()
extern.AttachThreadInput pid,thread_id,False
end function
Msgbox get_cursor()
FindWindow函数用于查找窗体
函数原型
HWND FindWindow(
LPCTSTR lpClassName, // pointer to class name
LPCTSTR lpWindowName // pointer to window name
);
lpWindowName是要查找窗体的标题,即这里的“无标题 - 记事本”。
如果找到窗体,函数返回该窗体的句柄;如果找不到,函数返回空值或者零 。
句柄和窗口标题,若只知其中之一,""要用vbNullString表示