Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

AutoCAD® .

NET: Developing a User Interface Using


WinForms
Gopinath Taget – Autodesk Inc.

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.

About the Speaker:


Gopinath is a member of the Autodesk Developer Technical Services Team. He has more than 5 years
of experience developing and supporting AutoCAD APIs, including ObjectARX, .NET, VBA and LISP.
Gopinath also has several years of experience in software development on other CAD platforms,
including Microstation, Solidworks, and CATIA -- mainly using C++ and technologies such as MFC and
COM. Gopinath was also involved in the development of Web-based applications for MapGuide and
AutoCAD Map. Gopinath has Masters Degrees in Civil Engineering and Software Systems.
Email: gopinath.taget@autodesk.com
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

AutoCAD® .NET: Developing a User Interface


Introduction
Welcome to the class “AutoCAD® .NET: Developing a User Interface”. In this class, we will
discuss the usage of the .NET User Interface API called Windows Forms (or WinForms) in an
AutoCAD .NET application. The following topics will be covered:

1) The .NET UI elements like controls (buttons, edit boxes, lists etc) and containers (Forms,
UserControl).

2) The Usage of .NET WinForms in an AutoCAD .NET application and issues specific to
AutoCAD:

a. Displaying Modal and Modeless Forms in AutoCAD


b. Interaction between Forms and AutoCAD editor and command line.
c. Integrating with AutoCAD Palettes
d. Integrating with other AutoCAD user elements like Options dialog and the tray

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 you‟ve never programmed before or used non-.NET based legacy APIs, then you‟re 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
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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

What this handout covers


This handout talks about a lot more than what is really covered in the AU class. The purpose of
the handout is to give a theoretical background of the .NET architecture and how it applies to
the AutoCAD programming environment.

We set out by discussing the evolution of .NET and why it was designed the way it is. We then
move on to discuss the various advantages and features of .NET programming and those that
will specifically help with .NET programming on AutoCAD. Finally we talk about the design
considerations of the AutoCAD .NET UI API and finish off with some discussion on AutoCAD UI
API features (which is the real focus of the class at AU).

This handout should therefore be treated as supplemental material to the AU class. The more
focused material for the class (the PowerPoint presentations and the samples) will also be
made available on the AU website in due course.

The .NET Framework


Programming in any technology is not an easy job. Every new technology that arrives on the
scene tries to solve issues that served as road blocks in preceding technologies and provide
new features in tune with the better hardware that we have. We saw this with the emergence of
COM, MFC and VB 5/6 and ATL (VB and ATL are technologies based on COM). Each of these
technologies evolved to solve a particular need that other technologies could not solve at all or
solved only to a limited extent.

For instance, MFC (Microsoft Foundation Classes) provided an “Object-Oriented” framework for
Windows programming that Win32 API (MFCs precursor) could not provide. COM (Component
Object Model) provided a programming infrastructure for easy version management and
deployment of our application “components”. VB 6 (Visual Basic 6) provided programming
environment for rapid application development. Many other smaller technologies too evolved
around these technologies such as DCOM (Distributed COM), ATL (Active Template Library, a
C++ based COM infrastructure) and WTL (Windows Template Library, a light-weight alternative
for MFC) to solve specific problems that the general technology could not solve.

3
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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

The Virtual Machine


A virtual machine in a very simplified sense is a “simulator” for an operating system. To
understand a virtual machine, we need to understand how a normal (non-.NET) application
works. When you launch the Word® application (which is not a .NET based application) for
instance, the operating system performs several operations directly on the application (load the
application into memory, call its entry point function and so on). i.e., the interaction between the
application and the operating system (OS) is direct with the OS managing the application
directly and the application calling directly into the OS for its services. While this can be a big
plus in terms of performance and control over what the application does, it can cause havoc
with the application (and in some cases with the OS) if the application is written badly.

A virtual machine solves this problem. The purpose of the virtual machine is to serve as the
“layer” between an application and the operating system and provide services to the application
similar to what the OS would. This has many advantages:

1) The application does not have direct access to the OS services and hence is less likely
to corrupt the system

4
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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 Sun‟s 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

5
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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.

The .NET Advantage


The .NET architecture was designed from the ground up with a strong emphasis on scalability.
Scalability depends on reusability, encapsulation and extensibility - all the attributes associated
with Object Oriented Design. So, all the languages that support or are supported by the .NET
architecture are highly Object Oriented by default. In fact, Microsoft has gone so far as to add
new language constructs to C++ and the old VB 6 language for it to be fully compliant with the
.NET design philosophy.

The .NET Windows Forms (or WinForms for short), a component of the .NET architecture,
conform to all these attributes. The WinForms API is built from the ground-up, is highly object-
oriented and scalable. There are several reasons why one may want to choose WinForms over
other UI technologies on Windows such as Win32, MFC or VB 6 (One can find a lot more
information on the internet regarding this7):

1. Direct access to the huge number APIs implemented as a part of the .NET API, such as
the database access APIs (ADO .NET), XML APIs and the multi-media APIs.
2. Rich choice of languages to implement one‟s functionality (C#, VB .NET, C++, etc.). This
allows for a gentler and quicker learning curve.
3. A very rich choice of visual controls and types (See Appendix A).
4. Robust memory management system that includes an asynchronous garbage collector.
5. Minimal code migration effort and dependence on compilers. For instance, the same
.NET DLL should work without recompile for both 32 bit and 64 bit platforms.
6. Uniform error handling mechanism enforced across the supported languages.

3 http://msdn2.microsoft.com/en-us/windowsvista/default.aspx
4 http://msdn.microsoft.com/msdnmag/issues/02/07/SharedSourceCLI/default.aspx
5 http://www.go-mono.com/
6 http://www.gnu.org/projects/dotgnu/
7 http://samples.gotdotnet.com/quickstart/winforms/

6
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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 AutoCAD‟s 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
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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 HowTo‟s 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

8
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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 http://msdn2.microsoft.com/en-us/library/ms973872.aspx
11 http://dotnet.sys-con.com/read/39039.htm
12 http://support.microsoft.com/kb/815774

9
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

The AutoCAD .NET UI API:

Introduction:
Significant effort was expended by the AutoCAD engineering team in implementing the “under
the hood” tie-in between the .NET platform and AutoCAD (though, the .NET framework makes it
very seamless). AutoCAD 2005 first integrated the .NET Framework and exposed a limited
.NET API that covers the ObjectDBX functionality (functionality related to DWG
drawing/database access). AutoCAD 2006 expanded on this.NET API and added coverage for
“application-level” functionality in AutoCAD and some less-used ObjectDBX functionality that
was not exposed for AutoCAD 2005.

Most of the AutoCAD .NET API types (classes) are implemented as thin wrappers over existing
C++ (ObjectARX) classes. The .NET wrappers are implemented in Managed C++. As already
discussed, managed C++ is an extension to the Standard C++ language with full support for the
.NET Framework. The advantage of using Managed C++ over other .NET languages is that it
affords seamless interoperability with unmanaged C++ code (in a mixed managed assembly).
Marshalling .NET managed data types to unmanaged C++ types is handled by the compiler.
The resulting wrapping code is deceptively simple.

AutoCAD .NET UI Design Considerations


One of the main concerns of the core AutoCAD engineering team designing the AutoCAD .NET
API was that frameworks and technologies to create user interfaces change every few years.
Therefore, it was not deemed appropriate to build a comprehensive UI framework based on any
of the currently popular technologies. The emphasis was on providing APIs that make sure
internal and 3rd party developers can use .NET technologies easily to create user interfaces that
look similar to AutoCAD‟s own and blend well with the existing UI.

The AutoCAD COM API and the .NET CUI API already provide classes to create menus and
toolbars that look exactly the same as that of AutoCAD‟s.

For other kinds of the UI where C++ developers would use the ObjectARX AdUi/AcUi classes,
the following API functionalities were considered:

1. Common UI elements:
a. Common dialogs: file, color, linetype, plotstyle, lineweight, textstyle, etc.
b. Common icons: upper-left icon for dialogs, pick point, pick entity icons
2. Support UI extension by WinForms:
a. Allow WinForm user control in Palettes
b. Allow WinForm user control in extensible tabbed dialogs (E.g.: Options Dialog)
c. Wrap Status Bar API and expose it to .NET clients

10
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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.

Displaying .NET Dialogs


To implement custom .NET forms in AutoCAD, applications can extend the .NET
System.Windows.Forms classes directly just as in any typical .NET application. Also typically, a
.NET developer would use a method like “Form.ShowDialog” to display the Form.
However, it is strongly advised that developers do not attempt to display .NET forms in
AutoCAD using generic .NET APIs (such as Form.ShowDialog) directly. They should instead
use the Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog and
ShowModelessDialog methods to display their custom forms. Using Form.ShowDialog in an
AutoCAD extension application may result in unexpected behavior. Here are a few specific
reasons for using ShowModalDialog and ShowModelessDialog methods:

1. One can automatically persist the position and size of .NET dialogs invoked with the
ShowModalDialog() and ShowModelessDialog() methods
2. These methods provide support for globalization
3. They automatically set up the Dialog UI properly with the AutoCAD icon.
4. Not using these methods have been known to cause problems with enabling/disabling
dialogs
5. The .NET application may not behave as desired especially when used in conjunction
with VBA

Typical usage of these methods:

Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(myForm);

And

Autodesk.AutoCAD.ApplicationServices.Application.ShowModalDialog(null, myForm, false);

Hiding Modal Forms during User Interaction


This is a unique requirement that AutoCAD based developers face very often. The scenario: A
modal form is displayed with some information about one‟s application. A modal form as many
are aware does not allow user interaction with the AutoCAD editor as long as it is displayed.
The modal form has to be closed before the control returns to the AutoCAD editor. This however
is not always possible; we may want to temporarily access the AutoCAD editor (to say pick a
point or select an entity) and return back to our Modal form to continue with our application‟s
workflow.

11
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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();
}

The object “ed” represents the AutoCAD editor.

Using .NET User Controls with AutoCAD .NET API


.NET User Controls (represented by the UserControl class) are extraordinarily useful UI
elements to the AutoCAD .NET UI developer. They are essentially similar to .NET Forms in that
they serve as containers for other controls. However they cannot be displayed directly like a
Form. They themselves need to be contained within other “regular” containers like Forms and
AutoCAD .NET Palettes. VB 6 and ATL developers can think of user controls are a throwback to
ActiveX controls that one could define in VB 6 and in C++ using ATL/COM. In fact, this analogy
is deeper than one may imagine. User Controls can be “exposed” as ActiveX controls to clients
that consume COM based controls. That means, a VB 6 or VBA or even an ObjectARX

12
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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.

Creating Custom palettes


One can use custom user controls created in .NET to create custom Palette Sets in AutoCAD.
Here is a code snippet from the ObjectARX SDK sample “samples\dotNet\DockingPalette”:

ps = new Autodesk.AutoCAD.Windows.PaletteSet("Test Palette Set",new Guid("63B8DB5B-10E4-


4924-B8A2-A9CF9158E4F6"));
ps.Load+=new Autodesk.AutoCAD.Windows.PalettePersistEventHandler(ps_Load);
ps.Save+=new Autodesk.AutoCAD.Windows.PalettePersistEventHandler(ps_Save);
ps.Style = Autodesk.AutoCAD.Windows.PaletteSetStyles.NameEditable |
Autodesk.AutoCAD.Windows.PaletteSetStyles.ShowPropertiesMenu |
Autodesk.AutoCAD.Windows.PaletteSetStyles.ShowAutoHideButton |
Autodesk.AutoCAD.Windows.PaletteSetStyles.ShowCloseButton;
ps.MinimumSize = new System.Drawing.Size(300,300);
ps.Add("Test Palette 1", new TestControl());

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

Adding Custom tabs to the AutoCAD “Options” dialog


One can add custom user controls created in .NET as custom tabs in the AutoCAD options
dialog. To display a custom tab dialog in the .NET API, there are two steps. The first step is to

13
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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.

Predefined Utility Dialogs


Some classes in the Autodesk.AutoCAD.Windows namespace provide access to AutoCAD
feature dialog boxes, such as Linetype and Color. These classes provide a ShowDialog method
that displays the form. When using these classes, an application automatically gains
persistence for its dialog box size and position settings. Here is a list of commonly used utility
dialogs:

Autodesk.AutoCAD.Windows.OpenFileDialog
Autodesk.AutoCAD.Windows.SaveFileDialog

14
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

Autodesk.AutoCAD.Windows.ColorDialog
Autodesk.AutoCAD.Windows.LinetypeDialog
Autodesk.AutoCAD.Windows.LineWeightDialog
Autodesk.AutoCAD.Windows.PlotStyleDialog

Typical usage of a utility dialog:

[CommandMethod("TestColorDlg")]
public void TestColorDlgMethod()
{
ColorDialog cd = new ColorDialog();
cd.SetDialogTabs(ColorDialog.ColorTabs.ACITab | ColorDialog.ColorTabs.TrueColorTab |
ColorDialog.ColorTabs.ColorBookTab);

cd.IncludeByBlockByLayer =true;
cd.Color =null;

cd.ShowDialog();

Status Bar Customization


The AutoCAD .NET API provides a number of useful types and methods to query and
customize the AutoCAD application status bar. Here are the types associated with this
functionality:

Autodesk.AutoCAD.Windows.StatusBar
Autodesk.AutoCAD.Windows.StatusBarItem
Autodesk.AutoCAD.Windows.Pane
Autodesk.AutoCAD.Windows.PaneCollection
Autodesk.AutoCAD.Windows.TrayItem
Autodesk.AutoCAD.Windows.TrayItemCollection
Autodesk.AutoCAD.Windows.TrayItemBubbleWindow
Autodesk.AutoCAD.Windows.DefaultPane
Autodesk.AutoCAD.Windows.PaneStyles
Autodesk.AutoCAD.Windows.TrayItemBubbleWindowCloseReason

And here is a typical usage scenario:

static TrayItem oneNewTi = null;


///
[CommandMethod("MyTray")]
public void TrayTest()
{
StatusBar sb = Application.StatusBar;

TrayItemCollection tis = sb.TrayItems;

15
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

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
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

 www.autodesk.com/developautocad - for a general overview of the AutoCAD APIs and


publicly available resources.

 www.autodesk.com/apitraining - if you‟re 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 Walmsley‟s 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
CP304-4 AutoCAD® .NET: Developing a User Interface Using WinForms

Appendix A:

Windows Forms Component Hierarchy (MSDN: http://msdn2.microsoft.com/en-


us/library/8w7ed3ba(vs.71).aspx):

18

You might also like