5

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

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

但是,当我在 IE 中运行它时,我收到错误“需要对象:'WScript'”。

在 IE 中有什么方法可以解决这个问题,或者有其他方法吗?我已经可以毫无问题地打开和操作 Word 文档。

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

更新:我的安全设置很低;所有 ActiveX 设置都启用(这是一个 Intranet 服务)。我测试了这个问题的代码,计算器打开没有问题。事实上,我让 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 发生了什么。

最终答案:

<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>
4

3 回答 3

3
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。

于 2015-03-05T23:01:26.907 回答
2

WScript 对象在 IE 中不存在,除非您自己创建它:
Set WScript = CreateObject("WScript.Shell")
但是如果安全设置不是非常低的级别,它将无法工作。

编辑:考虑到 Tmdean 的评论,这是工作代码:

'CreateObject("WScript.Shell")
Set wshShell = CreateObject("WScript.Shell")
wshShell.AppActivate("calculator")
于 2011-05-14T20:43:53.807 回答
0

诀窍是使用WScript.CreateObject()而不是简单CreateObject()地创建 IE 对象。

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

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

于 2015-04-01T22:33:43.533 回答