.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How to select a drawing object which is in AutoCAD File from a .Net Application?

17 REPLIES 17
SOLVED
Reply
Message 1 of 18
CodeBug
6341 Views, 17 Replies

How to select a drawing object which is in AutoCAD File from a .Net Application?

Hi All,

 

I am trying to create a small application in C#.Net where by clicking a button, I should be able to select a drawing object in the AutoCAD file to get the object's handle.

 

I am able to open the Drawing file from the application but unable to figure out how to get the drawing object handle by clicking on it through the application.

 

Can anyone help with a code example ?

17 REPLIES 17
Message 2 of 18
VB_Autocad_guy
in reply to: CodeBug

Okay Let's see If I understand: 

 

1- Click on AutoCAD Object (From Within AutoCAD)

2- Display the DBOject Handle or Get that String info and do something with it? 

 

  • One you'll need an Event  I believe it's DatabaseObjectSelected
  • Or PromptSelectionResult 

Okay so here's an example from the help file: slightly modified. 

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
 
[CommandMethod("SelectObjectsOnscreen")]
public static void SelectObjectsOnscreen()
{
  // Get the current document and database
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;
 
  // Start a transaction
  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Request for objects to be selected in the drawing area
      PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection();
 
      // If the prompt status is OK, objects were selected
      if (acSSPrompt.Status == PromptStatus.OK)
      {
          SelectionSet acSSet = acSSPrompt.Value;
 
          // Step through the objects in the selection set
          foreach (SelectedObject acSSObj in acSSet)
          {
              // Check to make sure a valid SelectedObject object was returned
              if (acSSObj != null)
              {
                  // Open the selected object for write
                  Entity acEnt = acTrans.GetObject(acSSObj.ObjectId,
                                                   OpenMode.ForWrite) as Entity;
if (acEnt != null) {
//This IS WHERE YOU CAN GET THE HANDLE
//Sorry I'm usually in VB.net so I don't know if this is right.
msgbox("My Entity's Handle is: " & acEnt.Handle);
// Change the object's color to Green acEnt.ColorIndex = 3; } } } // Save the new object to the database acTrans.Commit(); } // Dispose of the transaction } }

 Give it a try. If not we'll keep helping you to you get it working. 

 

Good Luck!

Message 3 of 18
CodeBug
in reply to: VB_Autocad_guy

Thanks VB_Autocad_guy! You got it almost right. I want the selected objet's hanlde.

 

But while I used your code, I am getting the  error below as

 

The specified module could not be found. (Exception from HRESULT: 0x8007007E)

 

in Main function at the line

 

Application.Run(new frmMain());

 

frmMain is the form name where the button is placed and your code in the button click event.

 

 

Any idea why this this error is shown ? So far what I have come to know is

"The error is occurring when the .Net runtime JITs method you're about to step into, because it couldn't find one of the types used by the method."

 

Any help is appreciated.

Message 4 of 18
norman.yuan
in reply to: CodeBug

You cannot run the code shown in the other reply in you standalone EXE application. The code can only run inside AutoCAD as NETLOADed .NET DLL.

 

If you have to do use EXE app, you would look into AutoCAD COM API (COM automation).

Message 5 of 18
arcticad
in reply to: norman.yuan

Imports Autodesk
Imports Autodesk.AutoCAD.Interop

Public Class SelectOnScreen

    Private Sub SelectOnScreen_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SelectHandle()
    End Sub

    Sub SelectHandle()
        Dim acadDoc As AutoCAD.Interop.AcadDocument = Nothing

        Try
            acadApp = GetObject(, "AutoCAD.Application.18")
        Catch ex As Exception
        End Try

        If acadApp Is Nothing Then
            MessageBox.Show("Unable to Connect to AutoCAD", "AutoCAD Message", _
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If

        Dim sset As AcadSelectionSet

        SsetMake(acadApp.ActiveDocument, "sset")
        sset = acadApp.ActiveDocument.SelectionSets.Item("sset")
        sset.SelectOnScreen()

        For Each item As Object In sset
            MsgBox(item.handle)
        Next

    End Sub

    Public Sub SsetMake(ByVal thisDrawing As AutoCAD.Interop.AcadDocument, ByVal ssetname As String)
        Dim sset As AcadSelectionSet
        Dim ssetcheck As Boolean
        For Each sset In thisDrawing.SelectionSets
            If sset.Name = ssetname Then
                ssetcheck = True
                Exit For
            End If
        Next
        If ssetcheck Then
            thisDrawing.SelectionSets.Item(ssetname).Delete()
            sset = thisDrawing.SelectionSets.Add(ssetname)
        Else
            sset = thisDrawing.SelectionSets.Add(ssetname)
        End If
    End Sub
End Class

 

---------------------------



(defun botsbuildbots() (botsbuildbots))
Message 6 of 18
VB_Autocad_guy
in reply to: arcticad

Thanks Norman and articad for the help. 

 

Codebug - Hopefully you are up and running now!

Message 7 of 18
CodeBug
in reply to: VB_Autocad_guy

Thanks everyone!

 

VB_Autocad_guy:
I have converted the code by arcticad to C# and is definitly helpful but i'm waiting to see it working!

 

norman.yuan:

You pushed me back on track. thanks for that!

 

arcticad:
I have succesfully converted your code to C#.net but stuck at the line


For Each item As Object In sset
MsgBox(item.handle)     <<<<<<<<<<<<<<< Error line
Next


with error as

 

'object' does not contain a definition for 'handle'

 

I am not getting the Handle property for this object.

Please help..

 

Message 8 of 18
CodeBug
in reply to: arcticad

Also, SelectOnScreen without any arguments throws as eror as 

 

No overload for method 'SelectOnScreen' takes '0' arguments

 

What should be the arguments to this method ?

 

 

 


 


 

 

Message 9 of 18
arcticad
in reply to: CodeBug

just put null in the first argument.

 

Can you post your c# code?

Thanks

---------------------------



(defun botsbuildbots() (botsbuildbots))
Message 10 of 18
CodeBug
in reply to: arcticad

Hi Arcticad,


This is my code.

 

internal void SelectHandle()
        {
           if (Globals.AcadDoc == null)
            {		        
                System.Windows.Forms.MessageBox.Show("Unable to Connect to AutoCAD");
		        return;
	        }

	        AcadSelectionSet sset = default(AcadSelectionSet);

            SsetMake(Globals.AcadDoc, "sset");
            sset = Globals.AcadDoc.SelectionSets.Item("sset");
            sset.SelectOnScreen();            
	        foreach (object item in sset) {                		        
                System.Windows.Forms.MessageBox.Show(item.handle);
               }
        }

 1. Error in line

 

sset.SelectOnScreen(); 

 

Error:

No overload for method 'SelectOnScreen' takes '0' arguments

 

2. Error in line

 

System.Windows.Forms.MessageBox.Show(item.handle);

 

Error:

'object' does not contain a definition for 'handle'

 

Thanks for staying with this!

Message 11 of 18
Balaji_Ram
in reply to: CodeBug

Hi,

 

The issue sound similar to what is discussed in this post :

http://adndevblog.typepad.com/autocad/2012/05/how-to-pass-com-optional-parameter-in-c.html

 

 



Balaji
Developer Technical Services
Autodesk Developer Network

Message 12 of 18
norman.yuan
in reply to: CodeBug

I believe the error you got is compiling error, not runtime error. That is, your code does not compile.

 

1. The first compiling error:

 

Not like VB, in C#, you need to pass parameteres for the optional argument:

 

SelectOnScreen(Type.Missing, Type.Missing);

 

2. The second compiling error: that is because C# is strong type language, ab "object" natually does not have property that from an specific class instance. YOu need to cast the "object" into a correct specific type before to access the property. In your case, you need:

 

foreach (object item in sset)

{

    AcadEntity ent=item as AcadEntity;

    if (ent!=null)

    {

        MessageBox.Show(string.Format("Entity Handle={0}", ent.Handle));

    }

}

 

It looks like more .NET programming (not AutoCAD specific) learning is due.

Message 13 of 18
CodeBug
in reply to: Balaji_Ram

Hi Balaji_Ram,

 

Yes I had already found this solution and this line of the code is working.

Thanks for your pointer !

Message 14 of 18

coud you show me event DatabaseObjectSelected.please!!!

ko0ls
Message 15 of 18
mchan01
in reply to: 01688686718

Is it possible to use that handle to create an object? lets say i saved that value of the handle on a table or xml file. Then use it on a new drawing as a object? if yes, i can't seem to find a way to do it.
Message 16 of 18
kdub_nz
in reply to: mchan01


mchan01 wrote:
Is it possible to use that handle to create an object? lets say i saved that value of the handle on a table or xml file. Then use it on a new drawing as a object? if yes, i can't seem to find a way to do it.

Not directly. The Handle is is just a number, which could mean anything in isolation.

You would also need to save the document qualified fileName that the object represented by the handle lives in.

 

You can then open the originating file and copy/reproduce the object represented by the handle into your current document.

 

 

//

Everything will work just as you expect it to, unless your expectations are incorrect.

class keyThumper<T> : Lazy<T>;      another  Swamper

Message 17 of 18
mchan01
in reply to: kdub_nz

What does it mean by document qualified name? Sorry to have asked this question.

 Actually what i am doing is creating a style(any style) 

 

Ex. Created PointCloudStyle


I was told that i only need the handle to do that, i was able to save it on the xml but now i am stuck on how to create an object from it.

 

I want it to be reusable, like if anyone retrieves that entry from our xml, a pointcloudstyle will automatically be created for the user.
 

is that possible? 

Message 18 of 18
arcticad
in reply to: mchan01

Just to clarify the conversation, The handle is a unique number that identifies an entity within the drawing. It has no other meaning to the program.

 

When you insert an object such as a block into a drawing it will receive a new unique handle in that drawing,.

 

You can deep clone a database object from one drawing into another. This will also give it a new unique number.

 

If you wanted to store an objects properties you would need a store all of it's properties such as aline's end and startpoint, Layers etc as text in your excel sheet.

 

Then recreate the object as a new object and fill in each of the properties.

---------------------------



(defun botsbuildbots() (botsbuildbots))

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost