这个问题可能有点老了,但我认为这个答案可能仍然可以提供帮助。(用 Excel VBA 测试,用 Access 无法测试)
WshShell.Exec 方法允许使用 .StdIn、.StdOut 和 .StdErr 函数来写入和读取 consol 窗口。WshShell.Run 方法不允许此功能,因此出于某些目的需要使用 Exec。
虽然确实没有内置函数来启动最小化或隐藏的 Exec 方法,但您可以使用 API 快速找到 Exec 窗口 hwnd 并最小化/隐藏它。
我下面的脚本从 Exec 对象中获取 ProcessID 来查找窗口的 Hwnd。然后,您可以使用 Hwnd 设置窗口的显示状态。
根据我对 Excel 2007 VBA 的测试,在大多数情况下,我什至看不到窗口......在某些情况下,它可能会在几毫秒内可见,但只会出现快速闪烁或闪烁......注意:我使用效果更好SW_MINIMIZE 比我用 SW_HIDE 做的更好,但你可以玩弄它。
我添加了 TestRoutine Sub 以展示如何使用“HideWindow”功能的示例。“HideWindow”函数使用“GetHwndFromProcess”函数从 ProcessID 中获取窗口 hwnd。
将以下内容放入模块...
Option Explicit
' ShowWindow() Commands
Public Const SW_HIDE = 0
Public Const SW_MINIMIZE = 6
'GetWindow Constants
Public Const GW_CHILD = 5
Public Const GW_HWNDFIRST = 0
Public Const GW_HWNDLAST = 1
Public Const GW_HWNDNEXT = 2
Public Const GW_HWNDPREV = 3
Public Const GW_OWNER = 4
' API Functions
Public Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Public Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
Public Declare Function GetDesktopWindow Lib "user32" () As Long
Public Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Sub TestRoutine()
Dim objShell As Object
Dim oExec As Object
Dim strResults As String
Set objShell = CreateObject("WScript.Shell")
Set oExec = objShell.Exec("CMD /K")
Call HideWindow(oExec.ProcessID)
With oExec
.StdIn.WriteLine "Ping 127.0.0.1"
.StdIn.WriteLine "ipconfig /all"
.StdIn.WriteLine "exit"
Do Until .StdOut.AtEndOfStream
strResults = strResults & vbCrLf & .StdOut.ReadLine
DoEvents
Loop
End With
Set oExec = Nothing
Debug.Print strResults
End Sub
Function HideWindow(iProcessID)
Dim lngWinHwnd As Long
Do
lngWinHwnd = GetHwndFromProcess(CLng(iProcessID))
DoEvents
Loop While lngWinHwnd = 0
HideWindow = ShowWindow(lngWinHwnd, SW_MINIMIZE)
End Function
Function GetHwndFromProcess(p_lngProcessId As Long) As Long
Dim lngDesktop As Long
Dim lngChild As Long
Dim lngChildProcessID As Long
On Error Resume Next
lngDesktop = GetDesktopWindow()
lngChild = GetWindow(lngDesktop, GW_CHILD)
Do While lngChild <> 0
Call GetWindowThreadProcessId(lngChild, lngChildProcessID)
If lngChildProcessID = p_lngProcessId Then
GetHwndFromProcess = lngChild
Exit Do
End If
lngChild = GetWindow(lngChild, GW_HWNDNEXT)
Loop
On Error GoTo 0
End Function
ShowWindow 功能:http:
//msdn.microsoft.com/en-us/library/windows/desktop/ms633548%28v=vs.85%29.aspx
GetWindow 函数:http:
//msdn.microsoft.com/en-us/library/windows/desktop/ms633515%28v=vs.85%29.aspx
GetDesktopWindow 函数:http:
//msdn.microsoft.com/en-us/library/windows/desktop/ms633504%28v=vs.85%29.aspx
GetWindowThreadProcessId 函数:http:
//msdn.microsoft.com/en-us/library/windows/desktop/ms633522%28v=vs.85%29.aspx
如果您需要有关 API 工作原理的更多信息,可以通过快速的 google 搜索为您提供大量信息。
我希望这可以帮助...谢谢。