【发布时间】:2014-08-14 21:53:49
【问题描述】:
我已经浏览了一个小时,但还没有找到可以对此有所帮助的东西。我正在使用 C# 从 VS2013 中的 .NET API 打开 AutoCAD,但由于某种原因,我永远无法真正启动 AutoCAD。我正在使用以下代码:
using System;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
namespace IOAutoCADHandler
{
public static class ACADDocumentManagement
{
[CommandMethod("ConnectToAcad")]
public static void ConnectToAcad()
{
AcadApplication acAppComObj = null;
// no version number so it will run with any version
const string strProgId = "AutoCAD.Application";
// Get a running instance of AutoCAD
try
{
acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
}
catch // An error occurs if no instance is running
{
try
{
// Create a new instance of AutoCAD
acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);
}
catch //// STOPS HERE
{
// If an instance of AutoCAD is not created then message and exit
// NOTE: always shows this box and never opens AutoCAD
System.Windows.Forms.MessageBox.Show("Instance of 'AutoCAD.Application'" +
" could not be created.");
return;
}
}
// Display the application and return the name and version
acAppComObj.Visible = true;
System.Windows.Forms.MessageBox.Show("Now running " + acAppComObj.Name +
" version " + acAppComObj.Version);
// Get the active document
AcadDocument acDocComObj;
acDocComObj = acAppComObj.ActiveDocument;
// Optionally, load your assembly and start your command or if your assembly
// is demandloaded, simply start the command of your in-process assembly.
acDocComObj.SendCommand("(command " + (char)34 + "NETLOAD" + (char)34 + " " +
(char)34 + @"C:\Users\Administrator\Documents\All Code\main-libraries\IOAutoCADHandler\bin\Debug\IOAutoCADHandler.dll" + (char)34 + ") ");
acDocComObj.SendCommand("DRAWCOMPONENT");
}
}
不幸的是,它总是在嵌套的catch 语句处停止,并且总是在不打开 AutoCAD 的情况下显示弹出框。关于如何至少让 AutoCAD 为我打开的任何建议?
编辑:错误消息
【问题讨论】:
-
您对确切的问题不是很准确。无论如何,有几个建议:将“catch”语句更改为“catch (Exception e1)”和“catch (Exception e2)”。在 Visual Studio 调试器下运行程序,并在每个 catch 子句的第一条语句上放置断点。当异常被捕获时,你应该能够看到异常的确切类型,这应该(希望)给你一些线索。
-
@RenniePet 是的,意识到这一点并包含错误输出。
-
您是否将其作为 NETLOADed DLL 运行?如果是,那么 Application 对象是
Autodesk.AutoCAD.ApplicationServices.Application如果不是,那么[CommandMethod("ConnectToAcad")]属性会让我们感到困惑。 -
我是 CAD 专家,你为什么要把进程内和互操作混在一起?如果需要,您可以将两者放在同一个程序集中,但我会将它们排除在相同的类和命名空间之外。
-
检查这个常见的新手错误:所有 AutoCAD 参考都需要将“本地复制”设置为 false。我们都做到了。
标签: c# .net visual-studio-2013 autocad