How to close a file in Autocad using C# keeping acad.exe running?

后端 未结 6 1597
执念已碎
执念已碎 2020-12-19 19:32

I am using visual studio 2010 and I am having a .DWG file which I want to open in autocad. Till now I have used this.

Process p = new Process();
ProcessStart         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 20:29

    AutoCAD does have an api. there are 4 assemblys. Two for in-process and two for COM.

    inprocess : acdbmgd.dll acmgd.dll

    COMInterop : Autodesk.Autocad.Interop.dll Autodesk.Autocad.Interop.Common.dll

    this is a method that will open a new instance of AutoCAD or it will connect to an existing running instance of AutoCAD.

    you will need to load these .dlls into your project references.

    using Autodesk.AutoCAD.Interop;
    using Autodesk.AutoCAD.Interop.Common;
    
    namespace YourNameSpace {
    
    public class YourClass {
    
    AcadApplication AcApp;
    private const string progID = "AutoCAD.Application.18.2";// this is AutoCAD 2012 program id
    private string profileName = "<>";
    private const string acadPath = @"C:\Program Files\Autodesk\AutoCAD 2012 - English\acad.exe";
    
    public void GetAcApp()
        {
            try
            {
                AcApp = (AcadApplication)Marshal.GetActiveObject(progID);
    
            } catch {
                try {
                    var acadProcess = new Process();
                    acadProcess.StartInfo.Arguments = string.Format("/nologo /p \"{0}\"", profileName);
                    acadProcess.StartInfo.FileName = (@acadPath);
                    acadProcess.Start();
                    while(AcApp == null)
                    {
                        try { AcApp = (AcadApplication)Marshal.GetActiveObject(progID); }
                        catch { }
                    }
                } catch(COMException) {
                    MessageBox.Show(String.Format("Cannot create object of type \"{0}\"",progID));
                }
            }
            try {
                int i = 0;
                var appState = AcApp.GetAcadState();
                while (!appState.IsQuiescent)
                {
                    if(i == 120)
                    {
                        Application.Exit();
                    }
                    // Wait .25s
                    Thread.Sleep(250);
                    i++;
                }
                if(AcApp != null){
                    // set visibility
                    AcApp.Visible = true;
                }
            } catch (COMException err) {
                if(err.ErrorCode.ToString() == "-2147417846"){
                    Thread.Sleep(5000);
                }
            }
        }
        }
    }
    

    closeing it is as simple as

    Application.Exit();
    

    and forgive the code. its atrocious, this was one of my first methods when i just started developing...

提交回复
热议问题