Get AutoCAD.Application Instance

Get AutoCAD.Application Instance

shkangE79NB
Participant Participant
1,761 Views
2 Replies
Message 1 of 3

Get AutoCAD.Application Instance

shkangE79NB
Participant
Participant

Hi everybody.

 

I want to get an AutoCAD.Application instance.

However, an error occurs when GetActiveObject() is executed during the AutoCAD loading screen.

If I set a breakpoint and call GetActiveObject() after loading is finished, the instance is got well.

Is there an event or other method in .Net to use when the loading window ends?

 

internal class Program
{
    static void Main(string[] args)
    {
        AcadApplication objAcad = default(AcadApplication);
        const string strProgId = "AutoCAD.Application.24.1";

        Process myProcess = new Process();
        myProcess.StartInfo.FileName = @"C:\Program Files\Autodesk\AutoCAD 2022\" + "acad.exe";
        myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        myProcess.Start();
        
        try
        {
            objAcad = Marshal.GetActiveObject(strProgId) as AcadApplication;
            if (objAcad is null)
                throw new Exception("obj is null");
        }
        catch(Exception ex) // An error occurs if no instance is running
         {
            Type acType = Type.GetTypeFromProgID(strProgId);

            objAcad = (AcadApplication)Activator.CreateInstance(acType, true);
        }

        objAcad.Visible = true;
    }
}
0 Likes
Accepted solutions (1)
1,762 Views
2 Replies
Replies (2)
Message 2 of 3

itimdavid27
Explorer
Explorer
Accepted solution

Could you please clarify why you need to do all this manually instead of just calling new AcadApplication()I(if you can guarantee exact version of AutoCad Installed) or or ActivatorCreateInstance(acType) (version independent)? Both approaches should connect to running AutoCAD instance or run new one if none running.

0 Likes
Message 3 of 3

_gile
Consultant
Consultant

Hi,

Typically, this is done this way (see this topic from the documentation):

  AcadApplication acadApp = null;
  const string progId = "AutoCAD.Application.24.1";
 
  // Try to get a running instance of AutoCAD
  try
  {
      acadApp = (AcadApplication)Marshal.GetActiveObject(progId);
  }
  catch // An error occurs if no instance is running
  {
      try
      {
          // Try to create a new instance of AutoCAD
          acadApp = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(progId), true);
      }
      catch
      {
          // If an instance of AutoCAD is not created then message and exit
          System.Windows.Forms.MessageBox.Show(
		      "Instance of 'AutoCAD.Application' could not be created.");
 
          return;
      }
  }

 



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes