这会连续激活正在运行的每个XL进程:
Public Sub Test()
Dim varAry()
Dim iInstances As Long
Dim hWndDesk As Long
Dim hWndXL As Long
Dim x As Long
Dim var As Variant
On Error Resume Next
'---
hWndDesk = GetDesktopWindow
Do
iInstances = iInstances + 1
hWndXL = FindWindowEx(GetDesktopWindow, hWndXL, "XLMAIN", vbNullString)
If hWndXL <> 0 Then
ReDim Preserve varAry(iInstances)
'Get the next Excel window
varAry(iInstances) = hWndXL
Else
Exit Do
End If
Loop
'---
For x = 1 To UBound(varAry)
MsgBox varAry(x)
var = SwitchToThisWindow(hwnd:=varAry(x), BOOL:=False)
Next x
exit_Sub
End Sub
但是GetObject()不能连续应用于每个被激活的进程。我想使用这样的对象来计算每个进程下打开的工作簿的数量。
感谢您的帮助。
答案 0 :(得分:0)
下面的代码将计算找到的“父级”类的数量。
Imports System.Runtime.InteropServices
Public Class Form1
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindow( _
ByVal lpClassName As String, _
ByVal lpWindowName As String) As IntPtr
End Function
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function FindWindowEx(ByVal parentHandle As IntPtr, _
ByVal childAfter As IntPtr, _
ByVal lclassName As String, _
ByVal windowTitle As String) As IntPtr
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim handleCount As Integer
Dim hWnd As IntPtr
'ConsoleWindowClass is for "Command Prompt" / cmd.exe in Windows.
hWnd = FindWindow("ConsoleWindowClass", vbNullString)
If hWnd.ToInt32 <> 0 Then handleCount += 1
Do
hWnd = FindWindowEx(0, hWnd, "ConsoleWindowClass", vbNullString)
If hWnd.ToInt32 <> 0 Then
handleCount += 1
Else
Exit Do
End If
Loop
MessageBox.Show("Found " & handleCount.ToString() & " handles...", "Results", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
End Class
从历史上看,我总是使用Pat or JK's API Spy(自98年以来)获取VBA / 6友好视图,了解如何获取窗口句柄(为您生成vb代码,建议编辑它)< / p>
pInvoke.net是所有Win32 API的绝佳资源,例如上面示例中使用的FindWindow和FindWindowEx。检查每个链接,因为它们是如何正确实现这些功能的广泛示例。