本文介绍了VB.NET 中的 WScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我程序中的一段代码:

This is a snipet of code from my program:

WSHShell = WScript.CreateObject("WScript.Shell")

但由于某种原因,没有声明WScript".我知道这段代码可以在 VBScript 中工作,但我正在尝试让它与 vb.net 一起工作.怎么了?

But for some reason, "WScript" is not declared. I know that this code works in VBScript but i'm trying to get it to work with vb.net. Whats going wrong?

推荐答案

WScript 对象特定于 Windows Script Host,在 .NET Framework 中不存在.

The WScript object is specific to Windows Script Host and doesn't exist in .NET Framework.

实际上,所有 WScript.Shell 对象功能都可以在 .NET Framework 类中使用.因此,如果您要将 VBScript 代码移植到 VB.NET,您应该使用 .NET 类而不是使用 Windows Script Host COM 对象来重写它.

Actually, all of the WScript.Shell object functionality is available in .NET Framework classes. So if you're porting VBScript code to VB.NET, you should rewrite it using .NET classes rather than using Windows Script Host COM objects.


如果出于某种原因,无论如何您更喜欢使用 COM 对象,则需要将适当的 COM 库引用添加到您的项目中,以使这些对象可用于您的应用程序.对于 WScript.Shell,它是 %WinDir%\System32\wshom.ocx(或 %WinDir%\SysWOW64\wshom.ocx on64 位 Windows).然后你可以写这样的代码:


If, for some reason, you prefer to use COM objects anyway, you need to add the appropriate COM library references to your project in order to have these objects available to your application. In case of WScript.Shell, it's %WinDir%\System32\wshom.ocx (or %WinDir%\SysWOW64\wshom.ocx on 64-bit Windows). Then you can write code like this:

Imports IWshRuntimeLibrary
....
Dim shell As WshShell = New WshShell
MsgBox(shell.ExpandEnvironmentStrings("%windir%"))


或者,您可以使用


Alternatively, you can create instances of COM objects using

Activator.CreateInstance(Type.GetTypeFromProgID(ProgID))

然后使用后期绑定与他们合作.像这样,例如:

and then work with them using late binding. Like this, for example:

Imports System.Reflection
Imports System.Runtime.InteropServices
...

Dim shell As Object = Nothing

Dim wshtype As Type = Type.GetTypeFromProgID("WScript.Shell")
If Not wshtype Is Nothing Then
    shell = Activator.CreateInstance(wshtype)
End If

If Not shell Is Nothing Then
    Dim str As String = CStr(wshtype.InvokeMember(
        "ExpandEnvironmentStrings",
        BindingFlags.InvokeMethod,
        Nothing,
        shell,
        {"%windir%"}
    ))
    MsgBox(str)

    ' Do something else

    Marshal.ReleaseComObject(shell)
End If

这篇关于VB.NET 中的 WScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:04