首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AcadApplication在AutoCAD 2022中的定位与使用

AcadApplication在AutoCAD 2022中的定位与使用
EN

Stack Overflow用户
提问于 2022-01-12 13:54:49
回答 1查看 648关注 0票数 1

我试图了解如何让AutoCAD识别正在运行的实例。但是,我遇到了一个问题,在应用程序中不存在AcadApplication,如下面的代码所述。

我这样做是为了避免制作一个直接插件,而是一个可以单独与AutoCAD通信的WPF应用程序(创建一个工具包,它还可以提供与AutoCAD无关的功能)。如果这个方法是个坏主意,也可以让我知道,因为我正在寻找解决这个问题的最佳方法。

有谁能帮我把这段代码用于AutoCAD 2022?目前,这是在运行.NET框架4.7.2的WPF应用程序中运行的(AutoCAD的安装中包含了手动引用)

代码语言:javascript
运行
复制
using System.Windows;

using System.Runtime.InteropServices;
using System;

using aD = Autodesk.AutoCAD.ApplicationServices;

namespace
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        aD.Application.AcadApplication acAppComObj = null;
        const string strProgId = "AutoCAD.Application.22";

        public MainWindow()
        {
            InitializeComponent();

            acAppComObj = Marshal.GetActiveObject(strProgId) as aD.Application.AcadApplication;

            // Get a running instance of AutoCAD
            try
            {
                acAppComObj = (aD.Application.AcadApplication)Marshal.GetActiveObject(strProgId);
            }
            catch // An error occurs if no instance is running
            {
                try
                {
                    // Create a new instance of AutoCAD
                    acAppComObj = (aD.Application.AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);
                }
                catch (Exception)
                {
                    // If an instance of AutoCAD is not created then message and exit
                    MessageBox.Show("Instance of 'AutoCAD.Application' could not be created.");

                    return;
                }
            }
        }
    }
}

为了简洁地回答我的问题,我如何使用AcadApplication类型,以及从哪里访问它?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-31 23:37:10

这里有一个示例类,您可以使用它来开始。

我猜想,为什么不能启动AutoCAD实例有两个根本原因:

  1. 您不是在使用Autodesk.AutoCAD.Interop.AcadApplication引用
  2. ,而是为AutoCAD 2022

使用错误的progId

让这段代码试一试,然后看看是否可以向后工作以找到问题。

当您想要在没有直接插件的情况下启动AutoCAD / use AutoCAD时,您需要使用COM互操作对象,而不是Autodesk.AutoCAD.ApplicationServices。

另外,以下是您需要的新引用的路径:

C:\程序文件\Autodesk\AutoCAD 2022\Autodesk.AutoCAD.Interop.dll

C:\程序文件\Autodesk\AutoCAD 2022\Autodesk.AutoCAD.Interop.Common.dll

C:\程序文件(x86)\Reference\Assemblies\Microsoft\Framework.NETFramework\v4.7.2\Microsoft.VisualBasic.dll

代码语言:javascript
运行
复制
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;


namespace StackOverflow
{
    public partial class MainWindow : Window
    {


        public MainWindow()
        {
            InitializeComponent();
            bool isAutoCADRunning = Utilities.IsAutoCADRunning();
            if (isAutoCADRunning == false)
            {
                MessageBox.Show("Starting new AutoCAD 2022 instance...this will take a some time.");
                Utilities.StartAutoCADApp();
            }
            else
            {
                MessageBox.Show("AutoCAD already running.");
            }
            Utilities.SendMessage("AutoCAD started from WPF");
            MyDriver.CreateMyProfile();
            Utilities.SendMessage("Profile created:" + Utilities.yourProfileName);
            //MyDriver.NetloadMyApp(@"C:\YourPathFolderPath\custom.Dll");
        }
    }



    public class MyDriver
    {
        public static void CreateMyProfile()
        {
            bool isAutoCADRunning = Utilities.IsAutoCADRunning();
            if (isAutoCADRunning == false)
                Utilities.StartAutoCADApp();
            Utilities.CreateProfile();
        }

        public static void NetloadMyApp(String dllPath)
        {
            bool isAutoCADRunning = Utilities.IsAutoCADRunning();
            if (isAutoCADRunning == false)
                Utilities.StartAutoCADApp();
            Utilities.NetloadDll(dllPath);
        }
    }

    public class Utilities
    {
        [System.Runtime.InteropServices.DllImport("user32")]
        public static extern IntPtr GetWindowThreadProcessId(IntPtr hwnd, ref IntPtr lpdwProcessId);

        private static readonly string AutoCADProgId = "AutoCAD.Application.24.1";
        private static AcadApplication App;


        public static void SendMessage(String message)
        {   
            App.ActiveDocument.SendCommand("(princ \"" + message + "\")(princ)" + Environment.NewLine);
        }
            

        public static bool IsAutoCADRunning()
        {
            bool isRunning = GetRunningAutoCADInstance();
            return isRunning;
        }

        public static bool ConfigureRunningAutoCADForUsage()
        {
            if (App == null)
                return false;
            MessageFilter.Register();
            SetAutoCADWindowToNormal();
            return true;
        }

        public static bool StartAutoCADApp()
        {
            Type autocadType = System.Type.GetTypeFromCLSID(new Guid("AA46BA8A-9825-40FD-8493-0BA3C4D5CEB5"), true);
            object obj = System.Activator.CreateInstance(autocadType, true);
            AcadApplication appAcad = (AcadApplication)obj;
            App = appAcad;
            MessageFilter.Register();
            SetAutoCADWindowToNormal();
            return true;
        }

        public static bool NetloadDll(string dllPath)
        {
            if (!System.IO.File.Exists(dllPath))
                throw new Exception("Dll does not exist: " + dllPath);
            App.ActiveDocument.SendCommand("(setvar \"secureload\" 0)" + Environment.NewLine);
            dllPath = dllPath.Replace(@"\", @"\\");
            App.ActiveDocument.SendCommand("(command \"_netload\" \"" + dllPath + "\")" + Environment.NewLine);
            return true;
        }
      

        public static bool CreateProfile()
        {
            if (App == null)
                return false;
            bool profileExists = DoesProfileExist(App, yourProfileName);
            if (profileExists)
            {
                SetYourProfileActive(App, yourProfileName);
                AddTempFolderToTrustedPaths(App);
            }
            else
            {
                CreateYourCustomProfile(App, yourProfileName);
                AddTempFolderToTrustedPaths(App);
            }
            SetYourProfileActive(App, yourProfileName);
            return true;
        }


        public static bool SetAutoCADWindowToNormal()
        {
            if (App == null)
                return false;
            App.WindowState = AcWindowState.acNorm;
            return true;
        }






        private static bool GetRunningAutoCADInstance()
        {
            Type autocadType = System.Type.GetTypeFromProgID(AutoCADProgId, true);
            AcadApplication appAcad;
            try
            {
                object obj = Microsoft.VisualBasic.Interaction.GetObject(null, AutoCADProgId);
                appAcad = (AcadApplication)obj;
                App = appAcad;
                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            return false;
        }

        public static readonly string yourProfileName = "myCustomProfile";

        private static void SetYourProfileActive(AcadApplication appAcad, string profileName)
        {
            AcadPreferencesProfiles profiles = appAcad.Preferences.Profiles;
            profiles.ActiveProfile = profileName;
        }

        private static void CreateYourCustomProfile(AcadApplication appAcad, string profileName)
        {
            AcadPreferencesProfiles profiles = appAcad.Preferences.Profiles;
            profiles.CopyProfile(profiles.ActiveProfile, profileName);
            profiles.ActiveProfile = profileName;
        }

        private static bool DoesProfileExist(AcadApplication appAcad, string profileName)
        {
            AcadPreferencesProfiles profiles = appAcad.Preferences.Profiles;
            object pNames = null;
            profiles.GetAllProfileNames(out pNames);
            string[] profileNames = (string[])pNames;
            foreach (string name in profileNames)
            {
                if (name.Equals(profileName))
                    return true;
            }
            return false;
        }

        private static void AddTempFolderToTrustedPaths(AcadApplication appAcad)
        {
            string trustedPathsString = System.Convert.ToString(appAcad.ActiveDocument.GetVariable("TRUSTEDPATHS"));
            string tempDirectory = System.IO.Path.GetTempPath();
            List<string> newPaths = new List<string>() { tempDirectory };
            if (!trustedPathsString.Contains(tempDirectory))
                AddTrustedPaths(appAcad, newPaths);
        }

        private static void AddTrustedPaths(AcadApplication appAcad, List<string> newPaths)
        {
            string trustedPathsString = System.Convert.ToString(appAcad.ActiveDocument.GetVariable("TRUSTEDPATHS"));
            List<string> oldPaths = new List<string>();
            oldPaths = trustedPathsString.Split(System.Convert.ToChar(";")).ToList();
            string newTrustedPathsString = trustedPathsString;
            foreach (string newPath in newPaths)
            {
                bool pathAlreadyExists = trustedPathsString.Contains(newPath);
                if (!pathAlreadyExists)
                    newTrustedPathsString = newPath + ";" + newTrustedPathsString;
            }
            appAcad.ActiveDocument.SetVariable("TRUSTEDPATHS", newTrustedPathsString);
        }
    }


    public class MessageFilter : IOleMessageFilter
    {
        [DllImport("Ole32.dll")]
        private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, ref IOleMessageFilter oldFilter);

        public static void Register()
        {
            IOleMessageFilter newFilter = new MessageFilter();
            IOleMessageFilter oldFilter = null;
            CoRegisterMessageFilter(newFilter, ref oldFilter);
        }
        public static void Revoke()
        {
            IOleMessageFilter oldFilter = null;
            CoRegisterMessageFilter(null, ref oldFilter);
        }

        public int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo)
        {
            return 0;
        }

        public int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType)
        {
            if (dwRejectType == 2)
                // flag = SERVERCALL_RETRYLATER.

                // Retry the thread call immediately if return >=0 & 
                // <100.
                return 99;
            // Too busy; cancel call.
            return -1;
        }

        public int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType)
        {
            return 2;
        }
    }

    [ComImport()]
    [Guid("00000016-0000-0000-C000-000000000046")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    interface IOleMessageFilter
    {
        [PreserveSig]
        int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo);
        [PreserveSig]
        int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType);
        [PreserveSig]
        int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType);
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70682786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档