Blue Theme Orange Theme Green Theme Red Theme
 
HeaderAd
Home | Forums | Videos | Photos | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Office Interop » Drawing Visio Shapes in the Visio ActiveX Control using C# and .NET

Drawing Visio Shapes in the Visio ActiveX Control using C# and .NET

This article will get you started in using the Visio ActiveX control that allows you to use Visio inside of a .NET Windows Form. The article will step you through a simple example of drawing shapes inside a Visio Drawing and connecting the shapes together.

Author Rank:
Technologies: .NET 1.0/1.1, ActiveX, Windows Forms,Visual C# .NET
Total downloads : 1223
Total page views :  46398
Rating :
 4.67/5
This article has been rated :  3 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
VisioInDotNet.ZIP
 
ArticleAd
Become a Sponsor



Edited by Nina Miller

Figure 1 - Visio Control in a Windows Form

Introduction

One of the most powerful drawing tools on the market is Microsoft Visio for Office. However, if you want to create add-ins or applications for this tool, the documentation for controlling the API is scarce and hard to follow. Searching the Net for samples on using Visio inside of the ActiveX control can be daunting. It's even hard finding samples on how to do basic tasks, like drawing a shape inside the control. As a result, I decided to write my own sample that will help you get started drawing shapes in a Windows form using the Visio ActiveX Component. The sample will show you how to add the control to your toolbox, add a stencil, and connect two shapes together from the stencil.

***Note: If you are wondering: "How can I use the ActiveX control without Visio installed?", you can't. You need to have Visio installed on your machine in order to use the ActiveX control which means you need to own Visio. (I know this seems obvious to many reading this article, but I often get this question for other office products such as Microsoft Word and Microsoft Excel.) The ActiveX control does not stand alone, it talks directly to Visio through In-Place editing.

Installing in the Toolbox

To install the Visio ActiveX control into the tool box, simply right click on the Toolbox and pick ("Choose Items"). Then go to the COM tab as shown in figure 2 and select the Visio Active X Control, then click OK.

Figure 2 - Choosing the Visio COM componnet

This will install the Visio Component into your .NET Toolbox as shown in Figure 3:

Figure 3 - Visio Component inside the .NET Toolbox

Now you can simply drag the Visio control onto the Windows form as seen in figure 1.  We are now ready to program Visio in .NET.

Code

Like other office automation objects, Visio consists of an Application, Documents, and Windows. The document contains the shape data, and the window lets you trap window events and do view operations such as copy and paste. We will be working with two documents in Visio: (1) the stencil and (2) the page document. The stencil contains the shapes we want to draw to the page document. The Visio ActiveX control already provides us with an active document through the first page. However, the stencil document needs to be opened. We can use the OpenEx method in order to open an existing stencil. In this example, we open the Basic Shapes stencil. We then display the number of shapes in this stencil in our tool strip status bar.

The first shape we want to create in our page document is the triangle shape. All shapes are accessed through the Masters collection inside the stencil document. We use the Drop method to drop the triangle shape into the Visio Page. In the drop method we can specify where we want the shape to appear on the page. Coordinates in Visio start in the bottom left hand corner and are measured in inches. In this example, we drop a triangle on the lower left hand corner of the page at x=1.5", y=1.5". Next we drop a square in the upper right hand corner using the same Drop method at x=10", y=7.5".  (Note that the control is shown in landscape.)

Listing 1 - Drawing Shapes through Automation in the Visio Control

public void DrawSampleShapeConnection()
{

// get the current draw page
Visio.
Page currentPage = axDrawingControl1.Document.Pages[1];

// Load the stencil we want
Visio.
Document currentStencil = axDrawingControl1.Document.Application.Documents.OpenEx("Basic_U.vss", (short)Visio.VisOpenSaveArgs.visOpenDocked);

// show the stencil window
Visio.
Window stencilWindow = currentPage.Document.OpenStencilWindow();

// this gives a count of all the stencils on the status bar
int countStencils = currentStencil.Masters.Count;

toolStripStatusLabel1.Text = string.Format("Number of Stencils in {0} = {1}", currentStencil.Title, countStencils);
statusStrip1.Refresh();

// create a triangle shape from the stencil master collection
Visio.
Shape shape1 = currentPage.Drop(currentStencil.Masters["Triangle"], 1.50, 1.50);

// create a square shape from the stencil master collection
Visio.
Shape shape2 = currentPage.Drop(currentStencil.Masters["Square"], 10, 7.50);

// create a dynamic connector from the stencil master collection
Visio.
Shape connector = currentPage.Drop(currentStencil.Masters["Dynamic connector"], 4.50, 4.50);

// currentPage.Layout();

// connect the shapes together through the dynamic connector
ConnectShapes(shape1, shape2, connector);

}

Connecting Shapes

Finally, we want to connect the two shapes together. This is accomplished through a property in Visio Shape objects called Cells. Cells are properties inside a shape used for a particular purpose to manipulate the shape or query the shape. The closest analogy to the concept of a Cell is that of a Cell in an Excel SpreadSheet. The Cell is accessed from three levels: a section, then a row, and finally, a cell which represents a property inside a Visio Shape. The get_cellSRC method of a Visio Shape allows you to access a Visio Connector Cell using  these three parameters. In this specific example we use: (1) the VisSectionIndices.visSectionObject enum (2) the VisRowIndices.visRowXFormOut enum, and (3) the VisCellIndices.visXFormPinX enum to access cell connectors of our triangle and square shapes. There appears to be some rhyme or reason to the naming of the row and the cell enumeration. Rows start with visRow<property group>. Cells start with vis<property group><sub property>.

The way to connect two shapes together in Visio is to drop the connector shape on the diagram and then use the Cells to "glue" the shapes to the connector. The GlueTo method of a Cell will glue the connector Cell of one shape to another shape's connector Cell.

Listing 2 -

private static void ConnectShapes(Visio.Shape shape1, Visio.Shape shape2, Visio.Shape connector)
{

// get the cell from the source side of the connector

Cell beginXCell = connector.get_CellsSRC(

(short)VisSectionIndices.visSectionObject,

(short)VisRowIndices.visRowXForm1D,

(short)VisCellIndices.vis1DBeginX);

// glue the source side of the connector to the first shape

beginXCell.GlueTo(shape1.get_CellsSRC(

(short)VisSectionIndices.visSectionObject,

(short)VisRowIndices.visRowXFormOut,

(short)VisCellIndices.visXFormPinX));

// get the cell from the destination side of the connector

Cell endXCell = connector.get_CellsSRC(

(short)VisSectionIndices.visSectionObject,

(short)VisRowIndices.visRowXForm1D,

(short)VisCellIndices.vis1DEndX);

// glue the destination side of the connector to the second shape

endXCell.GlueTo(shape2.get_CellsSRC(

(short)VisSectionIndices.visSectionObject,

(short)VisRowIndices.visRowXFormOut,

(short)VisCellIndices.visXFormPinX));

}

The three sets of a parameters can be used in other ways to manipulate a shape. If we want to add an arrow to our connector, we can access three magic parameters to retrieve the cell that changes the arrow as shown in listing 3. Here we assign the FormulaU property in order to specify the shape of the arrow. You can experiment with other numbers to see what other arrows are produced. For example, while "5" produces a filled in arrow, "7" produces an arrow consisting of two lines.

Listing 3 - Adding an arrow to the connector

// add an arrow to the connector on its end point

Cell
arrowCell = connector.get_CellsSRC((short)VisSectionIndices.visSectionObject, (short)VisRowIndices.visRowLine, (short)VisCellIndices.visLineEndArrow);
arrowCell.FormulaU = "5";

Likewise, we would arrive at the same result by getting the cell directly from the set of cells in the connector shape itself.  We just need to know the name of the property index string containing the end arrow:

// add an arrow to the connector on its end point

connector.get_Cells(
"EndArrow").Formula = "=5";
 
Conclusion

Visio is a great drawing tool for creating everything from landscapes to CAD diagrams. Automating Visio can be accomplished with .NET through the COM Wrapper around the Visio ActiveX Control. Controlling Visio is a bit tricky, because you need to be aware of the properties that exist with Shapes and how to use them. As you become familiar with shapes and their properties, you can make Visio behave the way you wish within the boundaries of the Visio object model. Anyway, enjoy experimenting with the Visio Automation engine. Perhaps with the power of .NET and Visio you can create your own powerful product to draw in some customers for your own business.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
VisioInDotNet.ZIP
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
DeplementJacob7/11/2007
how to deploy this application on computer that does have visio
Reply | Email | Delete | Modify | 
 
 
VC.netmintara9/10/2007

Hello ,

How to draw circles, ovals, fill it with color at run time on a form using vc.net. Currently it is done in word by using insert ->picture->autoshapes but this is not fast enough.

Any help will be greatly appreciated.

Mintara

Reply | Email | Delete | Modify | 
 
Re: DeplementMukesh11/30/2007
hi
Reply | Email | Delete | Modify | 
Great !Abhishek9/8/2007
Just what I was looking for. Thanks a heap.
Reply | Email | Delete | Modify | 
Visio thru c#,plz helpMukesh11/29/2007
I have a list of shapes & connectors in visio page in c#. what is code for how to select/highlight connector in C# of visio 2003. plz reply at mukesh.wadhwa@honeywell.com Thanks & Regards Mukesh
Reply | Email | Delete | Modify | 
apply data graphic using .NETgeorge12/3/2007
can you tell me how to apply a data graphic to a shape using .NET? is this done using an activex control?
Reply | Email | Delete | Modify | 
visio active control in asp.net?Robert12/14/2007
Hi, is it possible to use visio shapes in ASP.NET? Pretty much the same as this tutorial (titled: Drawing Visio Shapes in the Visio ActiveX Control using C# and .NET). however using web forms instead of windows forms. any ideas?
Reply | Email | Delete | Modify | 
about the formFernando2/8/2009
hello, i have a question... i try to draw a class diagram, y use te uml stencils, i can draw the class and the connectors, but i cant set de properties from the clases and connectors from uml, only general properties...like the name... how you did this form? can i modify the form, the form from the example is the default? thanks a lot...!
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved