Autocad .Net Api Reference
Autocad .Net Api Reference
Autocad .Net Api Reference
CP 304-4
Good user interface design is paramount for any successful software application, and your AutoCAD .NET add-in is no exception. In this class, you will get an overview of the scale and range of Microsoft .NET WinForms features and how to use them effectively. We show you how to work with .NET WinForms, how to create custom palettes, and how to implement event handling so your interface can respond to actions initiated by the user. We also demonstrate creating reusable .NET controls that can be used easily across multiple .NET applications and in multiple scenarios.
3) Exposing .NET UI to older API technologies like VBA, ObjectARX and Lisp
Prerequisites
This class is for developers who are between beginners and intermediate levels and have played around a little with generic .NET programming. We also assume a certain level of comfort with the .NET framework architecture (though we cover the basic premise and theory of the .NET framework in some detail in this handout). This class does not assume that the attendees are experts on .NET programming though. If youve never programmed before or used non-.NET based legacy APIs, then youre probably better signing up for a hands on class to get you started. Also there are other AutoCAD .NET sessions during the week at AU. Attending one or all of these classes will help you understand the content of this session. CP318-3L Hands-On Introduction to C# .NET CP308-3 An Introduction to VB.NET CP214-4 AutoCAD .NET: Using .NET with your LISP Applications CP114-3L Going From VBA to VB.NET in 90 Minutes You can also download the AutoCAD .NET training from the link below. Lab one in this training will show you how to create a .NET project for AutoCAD: http://www.autodesk.com/developautocad 2
Some of the other classes at AU that you may find useful (though these are not beginner level classes): CP222-4 Maximize the .NET in AutoCAD .NET CP204-2 API for CUIx files and the Runtime Ribbon in AutoCAD CP114-5 AutoCAD .NET: UI Design featuring WPF, Part 1 CP118-2 AutoCAD .NET: UI Design Featuring WPF, Part 2 CP208-1 AutoCAD .NET: Developing for AutoCAD Using IronPython and IronRuby
However, as most of these technologies evolved, the technology architects realized that they could only go so far. The MFC framework was becoming too large, complex and unwieldy. Further, the problems that plague generic C++ (e.g. pointers, memory management) were also plaguing MFC. COM was not faring much better either. COM depended on the concept of interfaces which is like a contract between a COM application (called the COM server) and the COM client application that uses the COM server. The problem was this contract or interface was defined at a very low, binary level. There was too much dependence on how the functions were arranged in an interface and their location/address in memory. This made the COM system very sensitive to any changes (even subtle changes) to the interface and made COM Server very flakey and frustrating to use. Crashes would occur for no apparent reason and would be very difficult to diagnose. Further, the two offshoots of the COM architecture (ATL and VB 5/6) did not work as well with each other as one hoped. A complex component created in ATL was not very easy to use in VB and vice-versa. The .NET framework evolved to solve all the issues plaguing these technologies (memory management, complexity, binary dependency of the interfaces and more). This was done by building the technology from ground up without any explicit dependence on the predecessor technologies. The whole of .NET architecture revolves around two fundamental concepts: 1) The virtual machine 2) Application Metadata
2) The virtual machine can provide a lot more in terms of services than the OS does 3) The virtual machine can enforce a comprehensive standard for data types and data exchange irrespective of the hardware. This is particularly helpful because: a. An application that targets the virtual machine can run on any platform that has the virtual machine b. An application that targets with the virtual machine can interoperate with any application that targets the virtual machine. The virtual machine is not a new concept however. It has a proven record by technology predecessors like VB 6 and Suns Java1 technology as a highly productive way to develop software. The core portions of.NET called the Common Language Infrastructure are standardized2.
Application Metadata:
The application metadata in a simplified sense can be considered as the replacement for the binary contract of the COM interface. The metadata in .NET is a machine readable, high level description of all the classes, methods and data defined in a .NET application. This description is not dependent on the binary layout of the .NET classes and interfaces and hence is not limited by the problems that plagued COM. Further, the .NET framework specification (that encompasses metadata specification) has made the metadata specification as comprehensive as possible. Finally, the Metadata for a .NET application module is embedded in the module itself in a separate section of the module. So every .NET module is a combination of code, data and metadata descriptions of the code and data. This concept of metadata has revolutionized programming as it allows: 1) Easy and dependable description of .NET application interfaces 2) Every .NET application (or its modules) can be reliably interrogated for all the classes, methods and interfaces it exposes 3) Allows .NET to provide advanced services like: a. Dynamic generation of code just based on the metadata description b. Allow application to add rich, customized descriptions to the application classes and methods (we will see examples of this in its usage in AutoCAD) These advantages combined with that of the virtual machine makes the .NET framework a truly worthy successor to COM and MFC. Today, the .NET programming environment is the
1 http://java.sun.com/ 2 http://msdn2.microsoft.com/en-us/netframework/Aa569283.aspx
preferred development environment of the newer3 Windows platforms. Moreover, in addition to its commercial implementation, Microsoft offers a shared source code version of .NET called Rotor4 for the FreeBSD operating system. There are also 3rd party initiatives (Mono5 and DotGNU6) under way to port .NET for Linux. From the point of view of an AutoCAD developer, .NET offers the following opportunities: 1. Decrease the development cost 2. Increase the quality of new AutoCAD features 3. Provide a unified API environment for developers at all skill levels. We will discuss these opportunities in greater detail in the AU class. In the next section we dig a little deeper into the advantages the.NET architecture provided and how it can be harnessed for AutoCAD programming.
7. Window definitions (including that of its children) are provided as a class definition and not in a resource file. 8. User interaction happens through events which depend on a robust paradigm called delegates. 9. Integration of the UI for desktop and web based components of an application. This helps applications evolve a uniform look and feel for desktop clients as well as web clients. As one can see, many of the .NET features listed above help in quickly developing robust and maintainable applications and these features by themselves are reason a plenty to move towards .NET platforms for many developers among us. However, the most significant feature from the perspective of development on AutoCAD (and arguably the most relevant for many AutoCAD developers) is the incredibly powerful, rich and easy-to-use Interoperability Infrastructure of .NET. The .NET interoperability infrastructure allows .NET application to communicate with and use unmanaged applications (Unmanaged applications are non-.NET based applications) and APIs like Win32, MFC and ARX applications, COM based applications and APIs like VB 6 and ATL applications. These is particularly relevant to existing AutoCAD API users because, more often than not, these developers develop (or have developed) and maintain applications on top of AutoCAD that use legacy AutoCAD based APIs like Lisp, ActiveX/COM and ObjectARX. These applications have been developed over a number of years representing intellectual property and run into thousands (in some cases millions) of lines of code. Migrating all of this to .NET is not easy to say the least and could mean months if not years of effort. In some cases, it may be impossible to migrate applications completely to .NET. The most optimal solution in such cases is to have a maintainable balance between .NET and the legacy APIs. The .NET interoperability infrastructure is the answer to all the above scenarios. The interoperability infrastructure provides powerful technologies that allow seamless communication between ARX<->.NET and ActiveX<->.NET (As a side note, I highly recommend the excellent class CP214-4 AutoCAD .NET: Using .NET with your LISP Applications for developers with legacy lisp code). These technologies are described briefly in the following section .NET Interoperability. Finally, in the context of UI development, it is interesting to note that Winforms API is built on top of the Microsoft Win32 API. .NET UI components are therefore highly inter-operable with legacy applications that used Win32 or MFC (which is also based on Win32 API). This is very important from AutoCADs point of view since AutoCAD is primarily an MFC application and a reliable technology for interoperability between the MFC code and the .NET code would go a long way in allowing seamless integration of the .NET API into the AutoCAD framework. In summary, the .NET API framework provides a number of powerful features like complete Object-Orientation, vast API repository for different purposes, automatic memory management and robust error management. Combine this with the powerful Interoperability infrastructure and the affinity of the WinForms APIs to with 32 APIs, and we have a very sweet deal indeed! 7
In the following section, we very briefly touch upon the various interoperability technologies as a detailed description is not within the scope of this document. Readers are encouraged to research on the web for more information on these technologies.
.NET Interoperability
There are a few of approaches that one can adopt to establish communication between .NET API and native applications like Win32, MFC or COM (Please check the internet articles Microsoft HowTos QuickStarts Tutorial8, and Mixed (Native and Managed) Assemblies9 for more information):
COM Interoperability
COM interoperability provides support for producing and consuming COM objects from managed code. .NET Objects that are intended to be consumed by COM applications must be designed with interoperability in mind right from the start. Before a type can be consumed by a COM application, the type must meet the following requirements.
The managed (.NET) type (class, interface, struct or enum) must be public. It is strongly recommended that the class explicitly implement an interface, instead of exposing a class directly which contains all of the members of the class and all the members of its base classes. The members of the type that are being accessed from COM must be public, non-static instance members. Private, protected, internal, and static members are not accessible. If you need to instantiate the type from COM, it must have a public, default (parameter less) constructor.
COM interoperability also provides mechanisms that make it possible to use native COM objects (created in say VB 6 or ATL) from .NET code as well. This typically manifests itself as a .NET application using an ActiveX control created using either VB 6 or C++ (ATL/MFC). Most of the time, it is just a case of dragging and dropping the ActiveX component on to the .NET Form and the .NET infrastructure takes care of the gory details of wrapping the ActiveX component up behind-the-scenes so a .NET application can consume it.
Platform Invoke
The platform invoke service (also called P/Invoke or simply PInvoke) makes it possible to call functions that are exported from an unmanaged/C++ application. Using platform invoke is similar to calling the LoadLibrary and GetProcAddress Win32 API functions in C++, which call into an exported function. It is also similar to using a Declare statement in Visual Basic to declare and call Win32 functions. Each unmanaged function being called must have a corresponding managed method declaration in the .NET application. The method declaration can be provided as part of any
8
http://samples.gotdotnet.com/quickstart/howto/doc/Interop/Interop_Overview.aspx 9 http://msdn2.microsoft.com/en-us/library/x0w2664k(VS.80).aspx
class and is attributed with the DllImport attribute in C# or VB.NET to indicate that the method is implemented in unmanaged code.
Mixed-Managed Applications
Mixed assemblies (an assembly is a self-contained .NET application or library) are C++ applications that are capable of containing both unmanaged (non .NET) code and MSIL (.NET) code. It is important to note here that C++ is the only language environment that is capable of doing this (containing .NET as well as non-.NET code). This capability allows the mixed assemblies to call and be called by other .NET components (pure or mixed), while retaining compatibility with components that are entirely unmanaged. Using mixed assemblies, developers can author applications using a mixture of managed and unmanaged functionality. This makes mixed assemblies ideal for migrating existing Visual C++ applications to the .NET Platform. For example, an existing application (say an MFC or ARX application) consisting entirely of unmanaged functions can be brought to the .NET platform by recompiling just one module with the /clr compiler switch. This module is then able to use .NET features, but remains compatible with the remainder of the application. In this way, an application can be converted to the .NET platform in a gradual, piece-by-piece fashion. It is even possible to decide between managed and unmanaged compilation on a function-by-function basis within the same source file in an application. Please lookup the MSDN topic An Overview of Managed/Unmanaged Code Interoperability10 for more information. As a side note, there are a couple of interesting approaches that demonstrate a Win32-like architecture for .NET UI applications (Explained in the following articles: NET Makes Window Subclassing Easy - Tap into Windows OS messages11 and How to subclass windows in Windows Forms by using Visual C++ .NET or Visual C++ 200512). Given the ease with which one can mix native (unmanaged) and managed (.NET) code in a mixed managed application, the AutoCAD engineering team adopted this approach (using Mixed-Managed Components) to make the power of AutoCAD available via the .NET API. This is manifested by the fact that most of the AutoCAD .NET API classes and methods are just thin wrappers (implemented as mixed managed .NET libraries like acmgd.dll and acdbmgd.dll) over existing ObjectARX API classes and methods. Now that we have a good idea of the .NET framework and its potential as a good application development platform for AutoCAD, we will move on to discuss the AutoCAD .NET UI API. Specifically, we discuss of why the AutoCAD .NET UI API was designed the way it is and specifics of the UI API Architecture.
10
The majority of UI elements that the AutoCAD .NET API provides can be found under the Autodesk.AutoCAD.Windows namespace. We will discuss below some of the important APIs for AutoCAD specific .NET forms implementation.
And
Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(null, myForm, false);
11
A developer who has developed a generic .NET application before may be tempted to just hide the .NET form and restore it when we are done with the AutoCAD editor. This however causes a set of problems subtle enough to escape even the most experienced developers at first glance. For instance, a developer who hides the form also has to make sure, the AutoCAD editor is activated and the focus is set to it. That means extra code. However this is a very small problem compared to the real issue. Because of the way AutoCAD is architected, one has to be very careful about how AutoCAD switches between UI elements and how code that access AutoCAD resources (like the editor and entities) from a UI element does it. Not doing it right could mean an AutoCAD crash (we have seen that before!) with no clue as to what caused it. The AutoCAD .NET API makes it very simple and easy to implement user interaction without the need to worry about these issues. Specifically, the AutoCAD .NET class EditorUserInteraction helps us in wrapping up all the functionality that one needs to perform safe switching between a modal form and the AutoCAD editor. The typical usage of this code would look like this:
using (EditorUserInteraction edUsrInt = ed.StartUserInteraction(this)) { // Code to add a couple of entities to AutoCAD PromptPointOptions prPtOpts = new PromptPointOptions("\nPlease select a point to place the ellipse:"); PromptPointResult prPtRes = ed.GetPoint(prPtOpts); Utilities.AddEllipse(prPtRes.Value); prPtOpts.Message = "\nPlease select a point to place the circle:"; prPtRes = ed.GetPoint(prPtOpts); Utilities.AddCircle(prPtRes.Value); ed.WriteMessage("\nAdded an Entity"); edUsrInt.End(); // End the UserInteraction. this.Focus(); }
12
application can use the .NET User Control as an ActiveX control. As you may have guessed already, this is achieved using the .NET COM Interop infrastructure. Now for the official explanation: According to MSDN, the UserControl (Fully Qualified name: System.Windows.Forms.UserControl) gives one the ability to create controls that can be used in multiple places within an application or organization. One can include all the code needed for validation of common data you ask the user to input. Some examples of this are e-mail addresses, telephone numbers, and postal codes. Another efficient use of the user control is to simply preload a ComboBox or ListBox with static items you commonly use in almost every application; some examples of this are countries/regions, cities, states, and office locations. The following sections discuss a couple of scenarios where UserControls can be used within an AutoCAD .NET application.
Where TestControl is the user control in the code segment above. Some of the classes associated with palette sets are:
Autodesk.AutoCAD.Windows.Palette Autodesk.AutoCAD.Windows.PaletteSet Autodesk.AutoCAD.Windows.StateEventIndex Autodesk.AutoCAD.Windows.PaletteSetStyles Autodesk.AutoCAD.Windows.DockSides Autodesk.AutoCAD.Windows.PaletteSetTitleBarLocation
13
subscribe to notifications for when the options dialog is launched by passing the address of a member function to be called. Something like this:
public static void AddTabDialog() { Autodesk.AutoCAD.ApplicationServices.Application.DisplayingOptionDialog += new TabbedDialogEventHandler(TabHandler); }
The second step is to implement the callback function; the second argument passed into the callback is a TabbedDialogEventArgs object which we must use to call its AddTab member. AddTab takes a title string, and an instance of a TabbedDialogExtension object, which wraps our form. Within the constructor of TabbedDialogExtension, we pass a new instance of our form, and callback addresses for callbacks to handle OnOK, OnCancel or OnHelp. Here is the code snippet that demonstrates this:
private static void TabHandler(object sender, Autodesk.AutoCAD.ApplicationServices.TabbedDialogEventArgs e) { EmployeeOptions EmployeeOptionsPage = new EmployeeOptions(); e.AddTab("Acme Employee Options", new TabbedDialogExtension( EmployeeOptionsPage, new TabbedDialogAction(EmployeeOptionsPage.OnOk))); }
Where EmployeeOptions type is the user control in the code segment above. The examples above are just two of many other uses of the UserControl. Other uses of a user control include adding it to a .NET form and exposing as an ActiveX control. We will be discussing these scenarios in detail during the actual session at AU. In the following sections, we will be discussing some UI classes that the AutoCAD .NET API provides for free and serve purposes specific to the AutoCAD UI.
14
15
TrayItem oneTi = null; foreach (TrayItem ti in tis) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Tray -- {0}\n", ti.ToolTipText); oneTi = ti; } if (oneTi != null && oneNewTi == null) { oneNewTi = new TrayItem(); oneNewTi.Visible = true; oneNewTi.Icon = oneTi.Icon; oneNewTi.ToolTipText = "copy of " + oneTi.ToolTipText; tis.Add(oneNewTi); oneNewTi.MouseDown += new StatusBarMouseDownEventHandler(trayMouseDown); } TrayItemBubbleWindow bubble = new TrayItemBubbleWindow(); bubble.Text = "My Bubble Text"; bubble.Title = "My Bubble Title"; bubble.HyperLink = http://adn.autodesk.com; bubble.HyperText = "Very Cool site"; oneNewTi.ShowBubbleWindow(bubble); bubble.Closed += new TrayItemBubbleWindowClosedEventHandler(bubbleClosed); } static void trayMouseDown(Object o, StatusBarMouseDownEventArgs e) { TrayItem ti = (TrayItem) o; Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("Tray on Click-- {0}\n", ti.ToolTipText); ti.CloseBubbleWindows(); }
Conclusion
What we have covered in this document is a brief overview of the very rich capabilities of the AutoCAD .NET API that allow you in integrating your application UI with AutoCAD. We will be discussing these capabilities (and more like customizing context menus and creating tool palettes) in depth during the presentation. See you there!
Further reading
Here are a few places you can go to for more information on the AutoCAD .NET API:
16
www.autodesk.com/developautocad - for a general overview of the AutoCAD APIs and publicly available resources. www.autodesk.com/apitraining - if youre interested in attending classroom training delivered by the Autodesk Developer network team. www.autodesk.com/joinadn - to find out how becoming a member of the Autodesk Developer Network can help your application development efforts, including our members-only knowledgebase and unlimited technical support. www.objectarx.com to download the ObjectARX SDK, this includes AutoCAD .NET API documentation and samples. blogs.autodesk.com/through-the-interface Kean Walmsleys blog focusing primarily on AutodCAD APIs. Kean is senior manager of the global Autodesk Developer Technical Services team. discussion.autodesk.com/forum.jspa?forumID=152 the Autodesk public discussion group for the AutoCAD .NET API. Watch out for our regular ADN DevLab events. DevLab is a programmers workshop (free to ADN and non-ADN members) where you can come and discuss your AutoCAD programming problems with the ADN DevTech team.
17
18