这是我程序中的一段代码:
WSHShell = WScript.CreateObject("WScript.Shell")
但是由于某种原因,没有声明“WScript”。我知道这段代码在 VBScript 中工作,但我正试图让它与 vb.net 一起工作。怎么了?
最佳答案
WScript
对象特定于 Windows 脚本宿主,在 .NET Framework 中不存在。
实际上,所有 WScript.Shell
.NET Framework 类中提供了对象功能。因此,如果您将 VBScript 代码移植到 VB.NET,您应该使用 .NET 类而不是使用 Windows Script Host COM 对象来重写它。
如果出于某种原因,您更喜欢使用 COM 对象,则需要将适当的 COM 库引用添加到您的项目中,以使这些对象可用于您的应用程序。如果是 WScript.Shell
,它是 %WinDir%\System32\wshom.ocx(或 %WinDir%\SysWOW64\wshom.ocx 在 64 位 Windows 上)。然后你可以写这样的代码:
Imports IWshRuntimeLibrary
....
Dim shell As WshShell = New WshShell
MsgBox(shell.ExpandEnvironmentStrings("%windir%"))
或者,您可以使用创建 COM 对象的实例
Activator.CreateInstance(Type.GetTypeFromProgID(ProgID))
然后使用后期绑定(bind)与他们合作。像这样,例如*:
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,所以这段代码可能很难看;随时改进。
关于vb.net - VB.NET 中的 WScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590211/