質問

I was interested in the integration between Autocad and vb.net. The task is to let autocad automatically draw using vb.net code. The final project will allow me to automatically create cables drawing, starting from tmeplates and a csv file with info (and of course my plugin).

"user friendly" is the keyword for me. I don't like the implementations where the user has to type commands on autocad to install the plugin, and then to use it. For this reason i had 2 problems:

1) Find a method to let my users to easy install the plugin

2) Develop a easy to use plugin with graphic interface.

I found the solution and I want to share it with you.

EDIT: @David wolfe answered with a solution to automatically start the plugin in autocad 2012 and earlier, but my factory has only licenses for autocad 2011 and later.

役に立ちましたか?

解決 2

EDIT: @david wolfe wrote an answer to this question to automatically install the plugin in Autocad 2012 and higher, but i deal even with autocad 2011 and autocad 2000, then I found the following solution.

Problem 1 SOLUTION: the autocad plugin developed in vb.net is a dll file. To automatically load it when autocad is launched, autocad needs that the system registry is modified. To do it, i prefer a method that doesn't use autocad. I created a new "Windows Forms Application" project (called INSTALLER) in vb.net, in the default form i added 2 buttons: one that registers the plugin, and one that removes the plugin. Note: In this sample i decided that the dll plugin file must be placed in the same folder of the exe application that we are going to create(the INSTALLER). Here it is the code for our plugin installer/remover. First of all create a module and paste this code: (some of the comments and messages inside the code are in italian, you can easily translate them in your language with google translate)

Imports Microsoft.Win32

Module GeneralFunctions


    Public Sub RegisterModule()

        Dim regKey As RegistryKey
        Dim PathToDll As String
        If MsgBox("Suggerimento: copia questo eseguibile,la dll e gli altri file, in una cartella a piacere prima di avviare la registrazione." & vbCrLf & "Se sposterai successivamente i file, sarà necessario registrare nuovamente il modulo" & vbCrLf & "Proseguire?", MsgBoxStyle.YesNo) <> MsgBoxResult.Yes Then
            Exit Sub
        End If

        PathToDll = System.Windows.Forms.Application.StartupPath & "\SupportoCavi.dll"

        If Not (FileIO.FileSystem.FileExists(PathToDll)) Then
            MsgBox("Il file SupportoCavi.dll non è stato trovato nella cartella")
            Exit Sub
        End If

        On Error GoTo PercorsoNonTrovato

        regKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\Autodesk\AutoCAD", True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\
        Dim keysList() As String = regKey.GetSubKeyNames

        regKey = regKey.OpenSubKey(keysList(0), True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\
        keysList = regKey.GetSubKeyNames()
        regKey = regKey.OpenSubKey(keysList(0), True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\ACAD-9001:410\
        regKey = regKey.OpenSubKey("Applications", True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\ACAD-9001:410\Applications

        On Error GoTo CreazioneChiaveFallita
        regKey = regKey.CreateSubKey("cavi") 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\ACAD-9001:410\Applications\cavi
        regKey.SetValue("DESCRIPTION", "Modulo per la creazione di cavi e cablaggi")
        regKey.SetValue("LOADCTRLS", 2)
        regKey.SetValue("MANAGED", 1)
        regKey.SetValue("LOADER", PathToDll)
        MsgBox("Modulo registrato con successo. Apri autocad per usare il nuovo set di strumenti")
        Exit Sub




PercorsoNonTrovato:
        On Error Resume Next
        Dim more As String = ""
        If Not (IsNothing(regKey)) Then
            more = "Errore su chiave " & regKey.Name
        End If
        MsgBox("Percorso non trovato nel registro di sistema," & vbCrLf & "comunica la tua versione di autocad e questo messaggio di errore a me@me.com  " & vbCrLf & more)
        Exit Sub

CreazioneChiaveFallita:
        On Error Resume Next

        If Not (IsNothing(regKey)) Then
            more = "Errore su chiave " & regKey.Name
        End If
        MsgBox("Errore durante la registrazione del modulo," & vbCrLf & "comunica la tua versione di autocad e questo messaggio di errore a me@me.com  " & vbCrLf & more)
        Exit Sub



    End Sub

    Public Sub UnregisterModule()

        Dim regKey As RegistryKey

        On Error GoTo PercorsoNonTrovato

        regKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\Autodesk\AutoCAD", True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\
        Dim keysList() As String = regKey.GetSubKeyNames

        regKey = regKey.OpenSubKey(keysList(0), True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\
        keysList = regKey.GetSubKeyNames()
        regKey = regKey.OpenSubKey(keysList(0), True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\ACAD-9001:410\
        regKey = regKey.OpenSubKey("Applications", True) 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\ACAD-9001:410\Applications

        On Error GoTo EliminazioneChiaveFallita
        regKey.DeleteSubKeyTree("cavi") 'HKEY_CURRENT_USER\Software\Autodesk\AutoCAD\R18.1\ACAD-9001:410\Applications\cavi
        MsgBox("Modulo rimosso con successo dal registro di sistema.")
        Exit Sub




PercorsoNonTrovato:
        On Error Resume Next
        Dim more As String = ""
        If Not (IsNothing(regKey)) Then
            more = "Errore su chiave " & regKey.Name
        End If
        MsgBox("Percorso non trovato nel registro di sistema," & vbCrLf & "comunica la tua versione di autocad e questo messaggio di errore a emanuele.vacca@selex-si.com  " & vbCrLf & more)
        Exit Sub

EliminazioneChiaveFallita:
        On Error Resume Next

        If Not (IsNothing(regKey)) Then
            more = "Errore su chiave " & regKey.Name
        End If
        MsgBox("Errore durante la rimozione del modulo," & vbCrLf & "comunica la tua versione di autocad e questo messaggio di errore a emanuele.vacca@selex-si.com  " & vbCrLf & more)
        Exit Sub



    End Sub
End Module

Now you only need to call the RegisterModule() and UnregisterModule() Subroutines in order to register or unregister our plugin. This is my GUI for the Installer:

Installer

Problem 2 SOLUTION: To create an easy to use plugin, i think that the best is to use a graphical user interface. For this reason i created a palette, with buttons, dropdown menus and pictures. Each time that autocad is opened our plugin will be automatically loaded, and our palette created. The following code is an easy implementation where the palette could be personalized by you with your button and your code. First of all create a new project (create a Windows Control Library) and add the reference to the following components:

(depending on your version of autocad this path may change)

C:\Program Files\Autodesk\AutoCAD 2011\acdbmgd.dll

C:\Program Files\Autodesk\AutoCAD 2011\acmgd.dll

Then create a class and paste this code (note:there is some code of my implementation, like structures, but you can easily clear it up upon your needs. loadDatabase, for example is my custom routine that you may not need):

Imports Autodesk.AutoCAD.Runtime
Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.DatabaseServices
Imports Autodesk.AutoCAD.Geometry
Imports System.IO

Imports System.Reflection

<Assembly: ExtensionApplication(GetType(adskClass))> 

Public Class adskClass

    Implements IExtensionApplication

    Public currentPath As String

    Public templates() As template

    Public Structure template
        Dim title As String
        Dim description As String
        Dim previewPath As String
        Dim templatePath As String
    End Structure



    Public Sub Initialize() Implements Autodesk.AutoCAD.Runtime.IExtensionApplication.Initialize
        'get current path
        Dim myAssy As [Assembly]
        myAssy = [Assembly].GetExecutingAssembly
        currentPath = myAssy.Location
        currentPath = System.IO.Path.GetDirectoryName(currentPath)

        loadPalette()
        loadDatabase()
    End Sub

    Public Sub Terminate() Implements Autodesk.AutoCAD.Runtime.IExtensionApplication.Terminate
        myPaletteSet.Remove(0)
    End Sub

    ' declare a paletteset object, this will only be created once
    Public myPaletteSet As Autodesk.AutoCAD.Windows.PaletteSet
    ' we need a palette which will be housed by the paletteSet
    Public myPalette As UserControl1

    Public Sub loadPalette()
        ' check to see if it is valid
        If (myPaletteSet = Nothing) Then
            ' create a new palette set, with a unique guid
            myPaletteSet = New Autodesk.AutoCAD.Windows.PaletteSet("SUPPORTO CAVI") ', New Guid("D61D0875-A507-4b73-8B5F-9266BEACD596"))
            ' now create a palette inside, this has our tree control
            myPalette = New UserControl1(Me)

            ' now add the palette to the paletteset
            myPaletteSet.Add("Supporto Cavi", myPalette)
        End If

        ' now display the paletteset
        myPaletteSet.Visible = True





    End Sub



    Public Sub loadDatabase()

        Dim databaseFile As String = currentPath & "\modelli\database.csv"
        If Not (FileIO.FileSystem.FileExists(databaseFile)) Then
            MsgBox("Non ho trovato il file database.csv nella cartella modelli per il modulo SUPPORTO CAVI" & vbCrLf & databaseFile)
            Exit Sub
        End If

        'carica file database
        On Error GoTo erroreDuranteCaricamentoDatabase
        Dim tmpstream As StreamReader = File.OpenText(databaseFile)
        Dim strlines() As String
        Dim strline() As String

        strlines = tmpstream.ReadToEnd().Split(Environment.NewLine)
        ReDim templates(UBound(strlines))

        For i As Integer = 0 To UBound(templates)
            strline = strlines(i).Split(",")
            templates(i).title = strline(0)
            Dim tmpFileName = strline(1)
            templates(i).previewPath = currentPath & "\modelli\" & tmpFileName & ".png"
            templates(i).templatePath = currentPath & "\modelli\" & tmpFileName & ".dwg"
            templates(i).description = strline(2)
            myPalette.cableTemplate.Items.Add(templates(i).title)
        Next

        Exit Sub
erroreDuranteCaricamentoDatabase:
        MsgBox("Errore durante il caricamento del database per il modulo SUPPORTO CAVI." & vbCrLf & Err.Description)


    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub




End Class

Then in our userControl, switch from graphic view to code view and paste this code:

Imports Autodesk.AutoCAD.ApplicationServices
Imports Autodesk.AutoCAD.EditorInput
Imports Autodesk.AutoCAD.DatabaseServices

'Imports Autodesk.AutoCAD.Windows
Imports Autodesk.AutoCAD.Runtime


Public Class UserControl1

    Public parentClass As adskClass


    Public Sub New(ByVal parent As adskClass)
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        parentClass = parent
    End Sub

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

    End Sub

    End Class

'Now we create a class that will help us if we have objects that we want to drag and drop from the palette to the autocad draw area. this class detects when the object is "dropped" in the AutoCAD editor. It Inherits from Autodesk.AutoCAD.Windows.DropTarget. 

Public Class MyDropTarget
    Inherits Autodesk.AutoCAD.Windows.DropTarget

    Public Overrides Sub OnDrop(ByVal e As System.Windows.Forms.DragEventArgs)
        Dim ed As Editor = Application.DocumentManager.MdiActiveDocument.Editor

        Try
            Using docLock As DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument()
                'Run the AddAnEnt procedure if needed
                'adskClass.AddAnEnt()
            End Using

        Catch ex As System.Exception
            ed.WriteMessage("Error Handling OnDrop: " + ex.Message)
        End Try

    End Sub
End Class

Compile everything, copy the generated dll file in the installer path previously created and test it.

Now you are ready to add on your palette your graphic buttons, code and whatever you want to do with it.

This is the GUI of my palette on autocad: Palette

How to distribute it: I put in a folder the installer exe, the dll plugin, a readme file and eventually the templates or other files needed by your custom plugin. Then I Zip this folder and send it by e-mail to my users. By this way, the users only need to unzip the folder in their hard disk (in a not temporary path), to open the exe and to press "REGISTER PLUGIN" button. FINISH! Now the user can open autocad and use the plugin.

他のヒント

For 2012 and higher use the AutoCAD autoloader format introduced in 2012. The your installer just has to extract it to a folder and Autocad takes care of the rest.

http://adndevblog.typepad.com/autocad/2013/01/autodesk-autoloader-white-paper.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top