QTP自动化测试权威指南(7)

发表于:2015-02-28来源:uml.org.cn作者:不详点击数: 标签:自动化测
以下用一些用例来演示使用API解决通常遇到的问题。 问题 17-1.如何判断当前桌面最上面的为浏览器窗口 声明GetForeGroundWindow APIextern.Declare micLong,GetForegrou

  以下用一些用例来演示使用API解决通常遇到的问题。

  问题 17-1.如何判断当前桌面最上面的为浏览器窗口

'声明GetForeGroundWindow API
extern.Declare micLong,"GetForegroundWindow","user32.dll","GetForegroundWindow"

'获取最前面窗口的句柄
hwnd = extern.GetForegroundWindow()

'判断是否有包含此句柄的浏览器窗口
isBrowser = Browser("hwnd:=" &hwnd).Exist()
 
If isBrowser then
Msgbox "The top most window is a browser"
End if

  问题 17-2.如何获得Windows的环境变量 (注意不是QTP环境变量)

'变量声明
Dim s_EnvValue

'声明 API "GetEnvironmentVariable"
Extern.Declare micLong,"GetEnvironmentVariable","kernel32.dll","GetEnvironmentVariableA", _
micString,micString+micByRef,micLong

'获取全局变量 "TEMP" 值
Extern.GetEnvironmentVariable "TEMP",s_EnvValue,255 '会得到临时目录路径
MsgBoxs_EnvValue

  问题 17-3.如何使用Windwos API选中Listbox里的选项(item)

' 声明API
Extern.Declare micLong,"SendMessage","user32.dll","SendMessageA",micLong,micLong,micLong,micLong

' 设置Listbox选项item的消息
Const LB_SETSEL = &H185

'方法:根据index选中复选框
Function CheckListBox(hwnd, index)
extern.SendMessagehwnd, LB_SETSEL, True, index
end function

'方法:根据index取消选中复选框
Function UnCheckListBox(hwnd, index)
extern.SendMessagehwnd, LB_SETSEL, False, index
end function

  问题 17-4.如何取到一个文本框的背景色 (当验证必填项跟可选项底色不同时可用到)

'声明需要的 API
Extern.Declare micLong,"GetPixel","gdi32","GetPixel",micLong,micLong,micLong
Extern.Declare micLong,"GetWindowDC","user32","GetWindowDC",micLong
Extern.Declare micLong,"ReleaseDC","user32","ReleaseDC",micLong,micLong
Extern.Declare micLong,"GetDC","user32","GetDC",micLong
Extern.Declare micLong,"SetForegroundWindow","user32","SetForegroundWindow",micLong

Dim hDCSource
Dim hWndSource
Dim backColor
'取得控件的句柄
hWndSource = Window("Window").WinEdit("MandatoryField1").GetROProperty("hwnd")

'将窗口置于最上面,因为GetPixel方法只能针对可见像素使用
extern.SetForegroundWindowhWndSource

'取得设备上下文句柄
hDCSource = Clng(Extern.GetDC(hWndSource))

'取得相关控件的像素(1,1)点的背景色
backColor = Clng(Extern.GetPixel(hDCSource, Clng(1),Clng(1)))
MsgBoxbackColor

'释放设备上下文句柄
Extern.ReleaseDChWndSource, hDCSource

  问题 17-5.如何使用Windows API模拟键盘操作

'声明API:键盘事件keybd_event
extern.Declare micVoid,"keybd_event","user32" ,"keybd_event", _
micbyte,micbyte,miclong,miclon
'声明API:虚拟按键码映射MapVirtualKey
extern.Declare micLong,"MapVirtualKey","user32","MapVirtualKeyA", _
micLong, micLong

Const KEYEVENTF_EXTENDEDKEY = &H1
Const KEYEVENTF_KEYUP = &H2
Const KEYEVENTF_KEYDOWN = &H0

Sub KeyDown(KeyAscii)
keyCode = extern.MapVirtualKey(KeyAscii, 0)
  '触发按键按下事件
extern.keybd_eventKeyAscii, keyCode, KEYEVENTF_KEYDOWN, 0
End Sub

Sub KeyUp(KeyAscii)
keyCode = extern.MapVirtualKey(KeyAscii, 0)
 '触发按键抬起事件
extern.keybd_eventKeyAscii, keyCode, KEYEVENTF_KEYUP, 0
End Sub

Sub KeyPress(KeyAscii)
KeyDownKeyAscii
KeyUpKeyAscii
End Sub

原文转自:http://www.uml.org.cn/Test/201307084.asp