发布新日志

  • [论坛] GetTextLocation —— 依据文本值动态获取坐标进行点击、拖拽操作

    2009-08-20 11:28:18

    在实际工作中我们经常会遇到对一些不能被捕获的对象进行点击、拖拽操作,直接去录制可能得到的就是Object.Click xxx,yyy ,这样的代码健壮性和可维护性都非常的差。
    如果需要被操作的位置上有相对唯一的文本值,那么就可以考虑使用GetTextLocation方法来辅助我们来动态定位到预期的坐标,这样就不会因为界面位置一点点的变动导致脚本运行失败了。

    先在帮助文档中查找GetTextLocation方法看看,我们会惊奇的发现几乎所有的对象都能支持该方法,这就使得该方法的应用范围会比较广,帮助文档中的描述如下:
    Syntaxobject.GetTextLocation (TextToFind, Left, Top, Right, Bottom, [MatchWholeWordOnly])


    Syntax Details
    Argument Description
    TextToFind Required. A String value. The text string you want to locate.
    Left Required. A Variant value. The left coordinate of the search area within the window or screen.
    Top Required. A Variant value. The top coordinate of the search area within the window or screen.
    Right Required. A Variant value. The right coordinate of the search area within the window or screen.
    Bottom Required. A Variant value. The bottom coordinate of the search area within the window or screen.
    Note: Set the Left, Top, Right, and Bottom coordinates to -1 to search for the text string within the object’s entire window.
    MatchWholeWordOnly Optional. A Boolean value. If True, the method searches for occurrences that are whole words only and not part of a larger word. If False, the method does not restrict the results to occurrences that are whole words only. Default value = True


    下面我们来看一个运用GetTextLocation的实例

    先简单的描述下需求,现在需要点击自定义的菜单栏上的"Generate Report"按钮,但按钮控件不能被捕获,只能识别到整个菜单栏对象为VbWindow("Window").WinObject("Menu"),点击按钮的代码如下:

    CODE:

    '获取"Generate Report"文本在WinObject("Menu")中的坐标范围,并返回给L(left),T(top),R(right),B(bottom)
    VbWindow("Window").WinObject("Menu").GetTextLocation strText,L,T,R,B,True
    '点击该文本所在坐标区域的正中心位置
    VbWindow("Window").WinObject("Menu").Click (L+R)/2, (T+B)/2
    为了便于使用,我们也可以进行简单的封装,例如:

    CODE:

    Function  ClickText(objOB, strText)
       If objOB.Exist(1) Then
         objOB.GetTextLocation strText,L,T,R,B,True
         objOB.Click (L+R)/2, (T+B)/2
       Else
         Reporter.ReportEvent micFail , "Can not find the specified object!", ""
       End If
    End Function

    ClickText VbWindow("Window").WinObject("Menu"),"Generate Report"
    进行拖拽操作也是一样的,通过GetTextLocation方法来获取文本中心位置坐标,动态的做为Drag和Drop的参数,这样就能比较精确的完成拖拽操作。
    下面也举个简单的例子吧

    CODE:

    Sub MoveItemByText(objFrom,strFrom,objTo,strTo)
    Dim l,r,t,b,l1,r1,t1,b1
    'Drag Item by specified text
    objFrom.GetTextLocation strFrom, l, t, r, b
    objFrom.Drag (l+r)/2, (t+b)/2, 1

    ' Drop Item on specified text
    objTo.GetTextLocation strTo, l1, t1, r1, b1
    objTo.Drop (l1+r1)/2, (t1+b1)/2, 1
    End Sub
    '将hsjzfling从Names列表中拖拽到Result列表的Champion子列表中
    Set bjAct = VbWindow("frmOvertime").ActiveX("ActiveX").ActiveX("ActiveX").ActiveX("ActiveX")
    MoveItemByText objAct.VbTreeView("Names"), "hsjzfling", objAct.VbTreeView("Result"), "Champion"
Open Toolbar