using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
namespace MultipleConnect
{
public class PmConnect
{
[DllImport("ole32.dll")]
static extern int CreateBindCtx(uint reserved, out IBindCtx ppbc);
[DllImport("ole32.dll")]
public static extern void GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
private List<object> GetRunningInstances(string[] progIds)
{
List<string> clsIds = new List<string>();
foreach (string progId in progIds)
{
Type type = Type.GetTypeFromProgID(progId);
if (type != null)
clsIds.Add(type.GUID.ToString().ToUpper());
}
IRunningObjectTable Rot = null;
GetRunningObjectTable(0, out Rot);
if (Rot == null)
return null;
IEnumMoniker monikerEnumerator = null;
Rot.EnumRunning(out monikerEnumerator);
if (monikerEnumerator == null)
return null;
monikerEnumerator.Reset();
List<object> instances = new List<object>();
IntPtr pNumFetched = new IntPtr();
IMoniker[] monikers = new IMoniker[1];
while (monikerEnumerator.Next(1, monikers, pNumFetched) == 0)
{
IBindCtx bindCtx;
CreateBindCtx(0, out bindCtx);
if (bindCtx == null)
continue;
string displayName;
monikers[0].GetDisplayName(bindCtx, null, out displayName);
foreach (string clsId in clsIds)
{
if (displayName.ToUpper().IndexOf(clsId) > 0)
{
object ComObject;
Rot.GetObject(monikers[0], out ComObject);
if (ComObject == null)
continue;
instances.Add(ComObject);
break;
}
}
}
return instances;
}
public void TestROT()
{
string[] ProgIds =
{
"WORD.Application",
};
List<object> instances = GetRunningInstances(ProgIds);
foreach (object acadObj in instances)
{
try
{
}
catch
{
}
}
}
}
}
这样只能连接第一个打开的WORD文档,我需要任意连接打开的文档,望大神们指点,谢谢! |