有用点个赞留个言,谢谢...
/// <summary>
/// 返回指向IBindCtx(绑定上下文对象)的实现的指针
/// </summary>
/// <param name="reserved"></param>
/// <param name="ppbc"></param>
/// <returns></returns>
[System.Runtime.InteropServices.DllImport("ole32.dll")]
private static extern int CreateBindCtx(int reserved, out System.Runtime.InteropServices.ComTypes.IBindCtx ppbc);
/// <summary>
/// 根据进程ID获取运行实例
/// </summary>
/// <param name="processId"></param>
/// <returns></returns>
private static object GetComObjectFromProcessId(int processId)
{
System.Runtime.InteropServices.ComTypes.IRunningObjectTable runningObjectTable = null;
System.Runtime.InteropServices.ComTypes.IEnumMoniker monikerEnumerator = null;
System.Runtime.InteropServices.ComTypes.IBindCtx ctx = null;
try
{
//获取运行对象表
CreateBindCtx(0, out ctx);
ctx.GetRunningObjectTable(out runningObjectTable);
//运行对象表可枚举
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
//枚举运行对象表
IntPtr numFetched = new IntPtr();
System.Runtime.InteropServices.ComTypes.IMoniker[] monikers = new System.Runtime.InteropServices.ComTypes.IMoniker[1];
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
//获取当前运行对象显示名称
string runningObjectName = null;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
//判断进程ID是否一致
if (runningObjectName.IndexOf(processId.ToString()) != -1)
{
object objReturnObject = null;
runningObjectTable.GetObject(monikers[0], out objReturnObject);
return objReturnObject;
}
}
}
finally
{
if (runningObjectTable != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(runningObjectTable);
if (monikerEnumerator != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(monikerEnumerator);
if (ctx != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(ctx);
}
return null;
}
private SldWorks GetSwApp()
{
var myProcess = Process.Start(@"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\SLDWORKS.exe", "-r");
SldWorks swApp = null;
for (int h = 0; h < 30; h++)
{
Thread.Sleep(1000);
swApp = (SldWorks)GetComObjectFromProcessId(myProcess.Id);
if (swApp == null)
{
continue;
}
else
{
CommonTool.Log((h + 1) + "次后成功获取sw实例");
return swApp;
}
}
return null;
}
有用点个赞留个言,谢谢...