PDA

View Full Version : Autodesk University 2005: Code Download & Discussion



Bobby C. Jones
2006-01-31, 06:41 PM
I did a class this year at AU and thought I would share the example code here and open it up for discussion.

All of my examples are in C#. Many of the attendees requested VB.NET equivalents. Although I have a VB6 background, I have almost no experience in VB.NET. If anyone is willing to do a translation, I'll help with what I can!

Code Examples to follow...

Bobby C. Jones
2006-01-31, 06:52 PM
Example #1 - Adding tabs to the options dialog box



using System;



using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using AU2005.AcadApi;



namespace AU2005.AcadApi

{

//Pages 5 & 6 in the handout

public class OptionsDialogTabExample

{

//This method tells Autocad to run the OnDisplayingOptionsDialog method

//when the DisplayingOptionsDialog event is fired

[CommandMethod("CreateNewOptionsTab")]

public void AddNewOptionsTab()

{

acadApp.DisplayingOptionDialog += new TabbedDialogEventHandler(OnDisplayingOptionDialog);



//The Drafting Settings and Customization dialogs can also be captured

}



//This is the method that adds the tab and places the user control on it

private void OnDisplayingOptionDialog(object sender, TabbedDialogEventArgs e)

{

//Create an instance of the user control

Au2005UserControl AuOptionsTab = new Au2005UserControl();



//Add actions for the Ok button

//Actions can also be added for Cancel and Help

TabbedDialogAction onOkPress = new TabbedDialogAction(OnOk);



//Add the tab, the user control, and Ok/Cancel/Help handlers.

e.AddTab("AutoDesk University 2005", new TabbedDialogExtension(AuOptionsTab, onOkPress));

}



//This method runs when the Ok button on the Options dialog is pressed.

//It will run even if they never open the custom tab.

public void OnOk()

{

acadApp.ShowAlertDialog ("Ok Pressed.\nSee you at AU 2006!");

}

}

}

Bobby C. Jones
2006-01-31, 07:04 PM
Example #2 - Adding buttons to the status bar



using System;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using Autodesk.AutoCAD.Windows;



namespace AU2005.AcadApi

{

//Pages 7 & 8

public class PaneButtonsExample

{

#region Application Pane



[CommandMethod("CreateAppPane")]

public static void AddApplicationPane()

{

Pane au2005AppPaneButton = new Pane();



//Set the buttons properties

au2005AppPaneButton.Enabled = true;

au2005AppPaneButton.Visible = true;

au2005AppPaneButton.Style = PaneStyles.Normal;

au2005AppPaneButton.Text = "AU2005 App. Pane";

au2005AppPaneButton.ToolTipText = "Welcome to Autodesk University 2005!";



//Hook into the MouseDown event to run code when the button is pressed.

au2005AppPaneButton.MouseDown += new StatusBarMouseDownEventHandler(OnAppMouseDown);



//Add the button to the applications status bar

//Items can also be added to the tray area

acadApp.StatusBar.Panes.Add(au2005AppPaneButton);

}





private static void OnAppMouseDown(object sender, StatusBarMouseDownEventArgs e)

{

Pane paneButton = (Pane) sender;

string alertMessage;



if (paneButton.Style == PaneStyles.PopOut)

{

paneButton.Style = PaneStyles.Normal;

alertMessage = "The application button is activated.";

}

else

{

paneButton.Style = PaneStyles.PopOut;

alertMessage = "The application button is de-activated.";

}



acadApp.StatusBar.Update();



acadApp.ShowAlertDialog(alertMessage);

}



#endregion





//Document pane code not shown in the handout

#region Document Pane



[CommandMethod("CreateDocPane")]

public static void AddDocumentPane()

{

Pane au2005DocPaneButton = new Pane();



//Set the buttons properties

au2005DocPaneButton.Enabled = true;

au2005DocPaneButton.Visible = true;

au2005DocPaneButton.Style = PaneStyles.Normal;

au2005DocPaneButton.Text = "AU2005 Doc. Pane";

au2005DocPaneButton.ToolTipText = "Welcome to Autodesk University 2005!";



//Hook into the MouseDown event to run code when the button is pressed.

au2005DocPaneButton.MouseDown += new StatusBarMouseDownEventHandler(OnDocMouseDown);



//Add the button to the documents status bar

acadApp.DocumentManager.MdiActiveDocument.StatusBar.Panes.Add(au2005DocPaneButton);

}





private static void OnDocMouseDown(object sender, StatusBarMouseDownEventArgs e)

{

Pane paneButton = (Pane) sender;

string alertMessage;



if (paneButton.Style == PaneStyles.PopOut)

{

paneButton.Style = PaneStyles.Normal;

alertMessage = "The document button is activated.";

}

else

{

paneButton.Style = PaneStyles.PopOut;

alertMessage = "The document button is de-activated.";

}



acadApp.DocumentManager.MdiActiveDocument.StatusBar.Update();



acadApp.ShowAlertDialog(alertMessage);

}



#endregion

}

}

Bobby C. Jones
2006-01-31, 07:12 PM
Example #3 - Creating custom palettes



using System;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.Windows;



namespace AU2005.AcadApi

{



//Pages 8 & 9

public class ToolPalettesExample

{

private static PaletteSet au2005PaletteSet;


[CommandMethod("ShowPalette")]
public static void CreatePaletteSet()

{

if (au2005PaletteSet == null)

{

//Create a new palette set at a size of 300x500

au2005PaletteSet = new PaletteSet ("AU 2005 Palette Set Demo");

au2005PaletteSet.MinimumSize = new System.Drawing.Size(300,500);



//Add two palettes to the palette set

//The handout only shows adding a single tab

au2005PaletteSet.Add("Demo Palette", new AU2005.AcadApi.Au2005UserControl());

au2005PaletteSet.Add("Demo Palette 2", new AU2005.AcadApi.Au2005UserControl2());

}

au2005PaletteSet.Visible = true;

}





public static PaletteSet CustomPaletteSet

{

get

{

return au2005PaletteSet;

}

}





[CommandMethod("DockLeft")]

public static void DockLeft()

{

if (CustomPaletteSet != null)

{

CustomPaletteSet.Dock = DockSides.Left;

}

}



[CommandMethod("Undock")]

public static void UnDock()

{

if (CustomPaletteSet != null)

{

CustomPaletteSet.Dock = DockSides.None;

}

}

}

}

Bobby C. Jones
2006-01-31, 07:15 PM
Example #4 - Single entity selection



using System;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.DatabaseServices;



namespace AU2005.AcadApi

{

//Page 10

public class GetEntityExample

{

[CommandMethod("GetCircle")]

public void GetEntity ()

{

Editor currentEditor = Application.DocumentManager.MdiActiveDocument.Editor;



//Create a new entity selection options object and

//restrict it to selecting circles only

PromptEntityOptions entitySelectionOpts = new PromptEntityOptions("\nSelect Circle: ");

entitySelectionOpts.SetRejectMessage("\nOnly Circles may be selected.");

entitySelectionOpts.AddAllowedClass (typeof (Circle), true);



//Start the selection process

PromptEntityResult entitySelectionResult = currentEditor.GetEntity(entitySelectionOpts);



//If a circle was successfully selected, diplay its radius

if (entitySelectionResult.Status == PromptStatus.OK)

{

DisplayCircleRadius(entitySelectionResult.ObjectId);

}

}





private void DisplayCircleRadius(ObjectId circleId)

{

Editor currentEditor = Application.DocumentManager.MdiActiveDocument.Editor;



using (Transaction trans = currentEditor.Document.TransactionManager.StartTransaction())

{

Circle selectedCircle = (Circle) trans.GetObject(circleId, OpenMode.ForRead);



Application.ShowAlertDialog ("Radius: " + selectedCircle.Radius.ToString());

}

}

}

}

Bobby C. Jones
2006-01-31, 07:17 PM
Example #5 - Selection Sets



using System;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.DatabaseServices;

using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;



namespace AU2005.AcadApi

{

//Page 11

public class SelectionSets

{

[CommandMethod("ssExample")]

public void SelectSetExample()

{

Editor currentEditor = acadApp.DocumentManager.MdiActiveDocument.Editor;



//Set up an event handler to filter the selection set to dissallow circles

SelectionAddedEventHandler selectionAdded = new SelectionAddedEventHandler(OnSelectionAdded);

currentEditor.SelectionAdded += selectionAdded;



//Create a new selection set options object

PromptSelectionOptions ssOptions = new PromptSelectionOptions();

ssOptions.AllowDuplicates = true;

ssOptions.MessageForAdding = "\nSelect anything but circles: ";



//Start the selection process

currentEditor.GetSelection(ssOptions);



//Remove the event handler

currentEditor.SelectionAdded -= selectionAdded;

}



//Not in the handout

[CommandMethod("UnselectableCircles")]

public void AlwaysRemoveCircles ()

{

Editor currentEditor = acadApp.DocumentManager.MdiActiveDocument.Editor;

currentEditor.SelectionAdded += new SelectionAddedEventHandler(OnSelectionAdded);

}



//Not in the handout

[CommandMethod("SelectableCircles")]

public void AllowCircles ()

{

Editor currentEditor = acadApp.DocumentManager.MdiActiveDocument.Editor;

currentEditor.SelectionAdded -= new SelectionAddedEventHandler(OnSelectionAdded);

}





private void OnSelectionAdded(object sender, SelectionAddedEventArgs e)

{

using (Transaction ssTrans = acadApp.DocumentManager.MdiActiveDocument.TransactionManager.StartTransaction())

{

ObjectId[] selectedEntityIds = e.AddedObjects.GetObjectIds();

Entity selectedEntity;



//Loop through the selected objects

for (int entityIndex = 0; entityIndex < e.AddedObjects.Count; entityIndex++)

{

ObjectId selectedEntityId = selectedEntityIds[entityIndex];

selectedEntity = (Entity)ssTrans.GetObject(selectedEntityId, OpenMode.ForRead);



//Remove the circles

if (selectedEntity is Circle)

{

e.Remove(entityIndex);

}

}

}

}

}

}

Bobby C. Jones
2006-01-31, 07:19 PM
Example #6 - Jigging



using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.ApplicationServices;



namespace AU2005.AcadApi
{

//Pages 12 & 13
//New class derrived from the DrawJig class
public class JigExample : DrawJig
{
#region private member fields

private Point3d previousCursorPosition;

private Point3d currentCursorPosition;

private Entity entityToDrag;

#endregion





[CommandMethod("StartJig")]
public void StartJig()
{

//Initialize cursor position

//Use the geometry library to create a new 3d point object

previousCursorPosition = new Point3d (0,0,0);



entityToDrag = new Circle(new Point3d(0,0,0), new Vector3d (0,0,1), 6);



Application.DocumentManager.MdiActiveDocument.Editor.Drag(this);

}





//You must override this method

protected override SamplerStatus Sampler(JigPrompts prompts)

{

//Get the current cursor position

PromptPointResult userFeedback = prompts.AcquirePoint();

currentCursorPosition = userFeedback.Value;



if (CursorHasMoved())

{

//Get the vector of the move

Vector3d displacementVector = currentCursorPosition.GetVectorTo(previousCursorPosition);



//Transform the circle to the new location

entityToDrag.TransformBy(Matrix3d.Displacement(displacementVector));



//Save the cursor position

previousCursorPosition = currentCursorPosition;



return SamplerStatus.OK;

}

else

{

return SamplerStatus.NoChange;

}

}





//You must override this method

protected override bool WorldDraw(WorldDraw draw)

{

draw.Geometry.Draw(entityToDrag);



return true;

}





private bool CursorHasMoved ()

{

return !(currentCursorPosition == previousCursorPosition);

}

}

}

Bobby C. Jones
2006-01-31, 07:26 PM
Example #7 - Various Database examples


using System;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Geometry;



using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;



namespace AU2005.AcadApi

{

//Pages 13 to 17

public class DatabaseExamples

{

//Page14

//Digging into the database, symbol tables, and ObjectId's

[CommandMethod("ShowAllLayers")]

public void ShowAllLayers()

{

//Get the current editor object

Editor currentEditor = AcadApp.DocumentManager.MdiActiveDocument.Editor;



//Get the current database object

Database activeDatabase = currentEditor.Document.Database;



//Start a transaction

using(Transaction trans = activeDatabase.TransactionManager.StartTransaction())

{

//Open the layer table

ObjectId layertableId = activeDatabase.LayerTableId;

LayerTable layers = (LayerTable)trans.GetObject(layertableId,OpenMode.ForRead);



//Iterate the layerId's in the layer table

foreach (ObjectId layerId in layers)
{
//Open the layer for reading

LayerTableRecord layer = (LayerTableRecord)trans.GetObject(layerId, OpenMode.ForRead);



//Print the layer name to the command line
currentEditor.WriteMessage("\n" + layer.Name);
}

}

}





//Page 15

//Accessing databases in the editor and from a file

[CommandMethod("InsertBlock")]

public void InsertBlock()

{

string sourceFileName = @"C:\OftenUsedBlock.dwg";

string newBlockName = "OftenUsedBlock";



try

{

using(Database sourceDatabase = GetDatabaseFromFile(sourceFileName))

{

//Insert the entities from modelspace of the sourceDatabase into

//a new block table record of the working database

//AcadApp.DocumentManager.MdiActiveDocument.Database...

HostApplicationServices.WorkingDatabase.Insert(newBlockName, sourceDatabase, false);

}

}

catch (System.Exception e)

{

Application.ShowAlertDialog(e.Message);

}

}



public Database GetDatabaseFromFile(string fileName)

{

Database databaseFromFile = new Database(false, true);

databaseFromFile.ReadDwgFile(fileName, System.IO.FileShare.None, false, null);

return databaseFromFile;

}
}
}

Bobby C. Jones
2006-01-31, 07:30 PM
Example #7 Continued - Various Database examples

These methods were in the DatabaseExamples class from the previous post, but I had to remove them in order to shorten the post to the required size limit. Put these back in the class.



//Page 15 lists the steps, Page 17 lists the code

//Adding objects to a database

//The six steps revealed!

[CommandMethod("CreateCircle")]

public void DrawCircle ()

{

//Step one - Start a transaction

using (Transaction trans = StartActiveDatabaseTransaction())

{

//Step two - Create the new object

Circle newCircle = CreateCircle();



//Step three - Open the symbol table

BlockTableRecord modelSpace = OpenActiveModelSpaceForWrite(trans);



//Step four - Append the object to the symbol table

modelSpace.AppendEntity(newCircle);



//Step five - Inform the transactionmanager of the new object

trans.TransactionManager.AddNewlyCreatedDBObject(newCircle, true);



//Step six - Commit the transaction

trans.Commit();

}

}



private Transaction StartActiveDatabaseTransaction()

{

return HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction();

}



private Circle CreateCircle()

{

Point3d centerPoint = new Point3d(0, 0, 0);

Vector3d normal = new Vector3d(0, 0, 1);

double radius = 4.5;

return new Circle(centerPoint, normal, radius);

}



private BlockTableRecord OpenActiveModelSpaceForWrite(Transaction trans)

{

return (BlockTableRecord)trans.GetObject(GetActiveModelSpaceId(), OpenMode.ForWrite);

}



private ObjectId GetActiveModelSpaceId ()

{

using (Transaction trans = StartActiveDatabaseTransaction())

{

BlockTable bt = (BlockTable)trans.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead);



return (ObjectId) bt[BlockTableRecord.ModelSpace];

}

}







//Page 16

//Adding non graphic objects

//Variations of the six steps

public static ObjectId CreateLayer(string layerName, Database targetDatabase)

{

//Step one - Start a transaction

using (Transaction trans =targetDatabase.TransactionManager.StartTransaction())

{

ObjectId layerTableId = targetDatabase.LayerTableId;



//Step three - Open the symbol table

//This table has only been opened for reading

LayerTable layers = (LayerTable)trans.GetObject(layerTableId, OpenMode.ForRead);



if (layers.Has(layerName))

{

return layers[layerName];

}

else

{

//Step two - Create the new object

LayerTableRecord newLayer = new LayerTableRecord();

newLayer.Name = layerName;



//Step three - Open the symbol table for writing

layers.UpgradeOpen();



//Step four - Append the object to the symbol table

layers.Add(newLayer);



//Step five - Inform the transactionmanager of the new object

trans.TransactionManager.AddNewlyCreatedDBObject(newLayer, true);



//Step six - Commit the transaction

trans.Commit();



return newLayer.ObjectId;

}

}

}



[CommandMethod("CreateLayer")]

public void CreateLayer()

{

string newLayerName = "AU2005";

CreateLayer(newLayerName, HostApplicationServices.WorkingDatabase);

}

Bobby C. Jones
2006-01-31, 07:32 PM
Example #8 - Database event example



using System;



using AU2005.AcadApi;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;



namespace AU2005.AcadApi
{

//Code not in the handout!
public class DatabaseEventExample
{
private const string NEW_LINE_LAYER_NAME = "NewLines";


[CommandMethod("CaptureLines")]
public static void CaptureLines()
{
Database activeDatabase = AcadApp.DocumentManager.MdiActiveDocument.Database;


DatabaseExamples.CreateLayer(NEW_LINE_LAYER_NAME, activeDatabase);


activeDatabase.ObjectAppended += new ObjectEventHandler(OnObjectAppended);

}





[CommandMethod("StopCaptureLines")]
public static void StopCaptureLines()
{
Database activeDatabase = AcadApp.DocumentManager.MdiActiveDocument.Database;


activeDatabase.ObjectAppended -= new ObjectEventHandler(OnObjectAppended);
}





private static void OnObjectAppended(object sender, ObjectEventArgs e)
{
if (e.DBObject is Line)
{
Line newLine = e.DBObject as Line;

newLine.UpgradeOpen();

if (newLine.IsWriteEnabled)
{
newLine.Layer = NEW_LINE_LAYER_NAME;

}
}
}
}
}

RoSiNiNo
2006-02-17, 10:04 AM
Thank you for this codes, will have a look at them ;)

Roland Feletic

jonesb33145
2006-03-27, 02:19 AM
Thanks a ton Bobby. I didn't get a chance to get to your class this last AU and I wish I had...this is GREAT stuff!

pferreira
2006-06-25, 09:38 PM
I will see these code examples, because i am trying to learn ObjectArx and Autocad.Net.
Thanks for the posts

adam.edmonds
2006-07-07, 02:49 PM
I keep getting an AccessViolationException on the line containing ReadDWGFile. Do I need to set some sort of access level for the application. I have read/write access on the path containing the block file.

Thanks,
Adam

daniel.balogh678498
2014-08-19, 01:23 PM
Hi, I see this is an old post. :)

However, is there any way to exactly tell my new Pane WHERE to appear? Looping through the panes gives me no real information, where I will place my pane (using the insert method by defining an index) E.g. I'd like to place mine after the left set of Status switches. The only info I see is the Description wich varies by language Packs... I'm not familiar with C++, although I could try to get there by using the unmamanged object. But I have no Idea, how to get the items, don't know the method names, etc...
Can you give a hint, where to start please?
Thanks in advance,
Daniel


Example #2 - Adding buttons to the status bar



using System;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

using Autodesk.AutoCAD.Windows;



namespace AU2005.AcadApi

{

//Pages 7 & 8

public class PaneButtonsExample

{

#region Application Pane



[CommandMethod("CreateAppPane")]

public static void AddApplicationPane()

{

Pane au2005AppPaneButton = new Pane();



//Set the buttons properties

au2005AppPaneButton.Enabled = true;

au2005AppPaneButton.Visible = true;

au2005AppPaneButton.Style = PaneStyles.Normal;

au2005AppPaneButton.Text = "AU2005 App. Pane";

au2005AppPaneButton.ToolTipText = "Welcome to Autodesk University 2005!";



//Hook into the MouseDown event to run code when the button is pressed.

au2005AppPaneButton.MouseDown += new StatusBarMouseDownEventHandler(OnAppMouseDown);



//Add the button to the applications status bar

//Items can also be added to the tray area

acadApp.StatusBar.Panes.Add(au2005AppPaneButton);

}





private static void OnAppMouseDown(object sender, StatusBarMouseDownEventArgs e)

{

Pane paneButton = (Pane) sender;

string alertMessage;



if (paneButton.Style == PaneStyles.PopOut)

{

paneButton.Style = PaneStyles.Normal;

alertMessage = "The application button is activated.";

}

else

{

paneButton.Style = PaneStyles.PopOut;

alertMessage = "The application button is de-activated.";

}



acadApp.StatusBar.Update();



acadApp.ShowAlertDialog(alertMessage);

}



#endregion





//Document pane code not shown in the handout

#region Document Pane



[CommandMethod("CreateDocPane")]

public static void AddDocumentPane()

{

Pane au2005DocPaneButton = new Pane();



//Set the buttons properties

au2005DocPaneButton.Enabled = true;

au2005DocPaneButton.Visible = true;

au2005DocPaneButton.Style = PaneStyles.Normal;

au2005DocPaneButton.Text = "AU2005 Doc. Pane";

au2005DocPaneButton.ToolTipText = "Welcome to Autodesk University 2005!";



//Hook into the MouseDown event to run code when the button is pressed.

au2005DocPaneButton.MouseDown += new StatusBarMouseDownEventHandler(OnDocMouseDown);



//Add the button to the documents status bar

acadApp.DocumentManager.MdiActiveDocument.StatusBar.Panes.Add(au2005DocPaneButton);

}





private static void OnDocMouseDown(object sender, StatusBarMouseDownEventArgs e)

{

Pane paneButton = (Pane) sender;

string alertMessage;



if (paneButton.Style == PaneStyles.PopOut)

{

paneButton.Style = PaneStyles.Normal;

alertMessage = "The document button is activated.";

}

else

{

paneButton.Style = PaneStyles.PopOut;

alertMessage = "The document button is de-activated.";

}



acadApp.DocumentManager.MdiActiveDocument.StatusBar.Update();



acadApp.ShowAlertDialog(alertMessage);

}



#endregion

}

}