首页 文章

VBScript将重点放在IE中的一个窗口上

提问于
浏览
5

我正在更新一段旧代码,它使用VBScript在IE中拉出一个窗口 . 出于某种原因,它喜欢在IE背后开放 . 谷歌给了我以下几行在VBScript中设置窗口焦点:

set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.AppActivate("calculator")

但是,当我在IE中运行它时,我收到错误“Object required:'WScript' . ”

有没有办法在IE中,或其他方式来做到这一点?我已经打开并操作Word文档没有任何问题 .

编辑:为了澄清,我在浏览器(IE)中的<script type =“text / vbscript”>标签中运行它,并且在我甚至调用AppActivate之前,代码在第一行崩溃 .

Update :我的安全设置非常低;所有ActiveX设置都处于启用状态(这是一个Intranet服务) . 我测试了this问题的代码,计算器没有问题 . 事实上,我让AppActivate使用JavaScript,但它不能与VBScript一起使用 .

使用JavaScript:

<script type="text/javascript">
    function calcToFrontJ(){
        wshShell = new ActiveXObject("WScript.Shell");
        wshShell.AppActivate("Calculator");
    }
</script>

不工作VBScript:

<script type="text/vbscript">
    Public Function calcToFrontV()
        'Set WScript = CreateObject("WScript.Shell") 'breaks with or without this line
        Set WshShell = WScript.CreateObject("WScript.Shell")
        WshShell.AppActivate("Calculator")
    End Function
</script>

我想我总是可以重构JavaScript,但我真的很想知道这个VBScript发生了什么 .

Final Answer:

<script type="text/vbscript">
    Public Function calcToFrontV()
        'must not use WScript when running within IE 
        Set WshShell = CreateObject("WScript.Shell")
        WshShell.AppActivate("Calculator")
    End Function
</script>

3 回答

  • 0

    IE中不存在WScript对象,除非您自己创建它:
    Set WScript = CreateObject("WScript.Shell")
    但是,如果安全设置不是很低,它就不会起作用 .

    编辑:在Tmdean的评论中考虑因素,这是工作代码:

    'CreateObject("WScript.Shell")
    Set wshShell = CreateObject("WScript.Shell")
    wshShell.AppActivate("calculator")
    
  • 2
    Set objShell = WScript.CreateObject("WScript.Shell")
    Set objIE = WScript.CreateObject("InternetExplorer.Application", "IE_")
    objie.navigate "url"
    objIE.Visible = 1
    objShell.AppActivate objIE
    
    'Above opens an ie object and navigates
    'below runs through your proccesses and brings Internet Explorer to the top.
    
    Set Processes = GetObject("winmgmts:").InstancesOf("Win32_Process")
    
    intProcessId = ""
    For Each Process In Processes
        If StrComp(Process.Name, "iexplore.exe", vbTextCompare) = 0 Then
            intProcessId = Process.ProcessId
            Exit For
        End If
    Next
    
    If Len(intProcessId) > 0 Then
        With CreateObject("WScript.Shell")
            .AppActivate intProcessId
    
        End With
    End If
    

    我今天在网上搜索了一小段时间,并将这些代码拼凑在一起 . 它确实有效:D .

  • 1

    诀窍是使用 WScript.CreateObject() 而不是普通 CreateObject() 来创建IE对象 .

    Set objShell = WScript.CreateObject("WScript.Shell")
    Set objIE = WScript.CreateObject("InternetExplorer.Application", "IE_")
    objIE.Visible = 1
    objShell.AppActivate objIE
    

    附:我在https://groups.google.com/forum/#!msg/microsoft.public.scripting.vbscript/SKWhisXB4wY/U8cwS3lflXAJ得到了Dan Bernhardt的解决方案

相关问题