我正在.Net 中编写一个 Windows 窗体应用程序来列出第三方 CAD/CAM 软件(在本例中为 CATIA)的所有正在运行的实例,并让用户选择其中一个来执行几个自动化任务。为了执行自动化任务,我需要获取 COM 对象的特定实例 - 与 Getobject() 相比,它给了我一个非特定的 COM 实例。有没有办法使用窗口句柄或任何其他方法获取特定的 COM 实例?
更新:正如雷蒙德所说,所有 COM 对象都没有单一的解决方案;但是我设法使用以下代码获取 CATIA COM 对象(使用 ROT 填充所有 CATIA COM 实例名称的列表):
<DllImport("user32.dll", CharSet:=CharSet.Auto)> Private Shared Sub GetClassName(ByVal hWnd As System.IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) End Sub
<DllImport("ole32.dll", ExactSpelling:=True, PreserveSig:=False)> Private Shared Function GetRunningObjectTable(ByVal reserved As Int32) As IRunningObjectTable End Function
<DllImport("ole32.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True, PreserveSig:=False)> Private Shared Function CreateItemMoniker(ByVal lpszDelim As String, ByVal lpszItem As String) As IMoniker End Function
<DllImport("ole32.dll", ExactSpelling:=True, PreserveSig:=False)> Private Shared Function CreateBindCtx(ByVal reserved As Integer) As IBindCtx End Function
Try
Dim ROTObject As Object = Nothing
Dim runningObjectTable As IRunningObjectTable
Dim monikerEnumerator As IEnumMoniker = Nothing
Dim monikers(1) As IMoniker
runningObjectTable = GetRunningObjectTable(0)
runningObjectTable.EnumRunning(monikerEnumerator)
monikerEnumerator.Reset()
Dim numFetched As IntPtr = New IntPtr()
While (monikerEnumerator.Next(1, monikers, numFetched) = 0)
Dim ctx As IBindCtx
ctx = CreateBindCtx(0)
Dim runningObjectName As String = ""
monikers(0).GetDisplayName(ctx, Nothing, runningObjectName)
runningObjectName = runningObjectName.ToUpper
If (Not runningObjectName.Equals("")) Then
Dim runningObjectIns As Object = Nothing
runningObjectTable.GetObject(monikers(0), runningObjectIns)
'Check if object is a Catia object
Try
Dim catiaIns As INFITF.Application = Nothing
catiaIns = DirectCast(runningObjectIns, INFITF.Application)
ListCATIA.Items.Add(catiaIns.Windows.Count)
Catch Exc As Exception
MessageBox.Show(Exc.ToString())
End Try
End If
End While
Catch Exc As Exception
Throw Exc
End Try
但是,所有 CATIA 实例均指加载的第一个 CATIA 应用程序。不知道为什么,有人吗?