Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Visual C# » 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 :
Page Views : 89324
Downloads : 2621
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
VisioInDotNet.ZIP
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Deplement by Jacob On July 11, 2007
how to deploy this application on computer that does have visio
Reply | Email | Modify 
VC.net by mintara On September 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 | Modify 
Re: Deplement by Mukesh On November 30, 2007
hi
Reply | Email | Modify 
Great ! by Abhishek On September 8, 2007
Just what I was looking for. Thanks a heap.
Reply | Email | Modify 
Visio thru c#,plz help by Mukesh On November 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 | Modify 
apply data graphic using .NET by george On December 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 | Modify 
visio active control in asp.net? by Robert On December 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 | Modify 
about the form by Fernando On February 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 | Modify 
Using .Net controls in visio add-in by Feng On September 25, 2009
Hi, Mike Gold,

Is it possible to use .Net controls to edit the shape's data in visio add-in, like using PropertyGrip to edit a customer shape data? 

In my case, I got a complicated customer data structure, which can not be easily defined by using visio's shape data, since visio's shape data only surpport simple data type, like string, number, boolean, variableList, fixedList, Duration. I need a more flexible UI to edit the customer data, so I am just wondering if it is possible to use PropertyGrid in visio add-in to edit my customer data. Thanks!

   
Reply | Email | Modify 
Drawing Visio Shapes in the Visio ActiveX Control using C# and .NET by pds On December 19, 2009
Hi Mike Gold,

 I successfully created flowchart dynamically  for my application as per the requirement with help of your nice article.an i integrated with this windows application as dll to web application in c#.But when i am sending request at very first time its working fine.when i sending second request  from the web it throws the Com exception..

Attempted to make calls on more than one thread in single threaded mode. (Exception from HRESULT: 0x80010102 (RPC_E_ATTEMPTED_MULTITHREAD))

in the line

this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.axDrawingControl1)).EndInit();

in form.designer.cs while  excuting
 public Form1()
        {           
           InitializeComponent();
        }

..am really fed up with this error to solve ..please kindly help me regarding this error.it will be grateful for you..thank you..


Reply | Email | Modify 
Help! by Thomas On February 17, 2010
Hey I need to fins out how to compare a shape to its master shape does any one know how to that?
Reply | Email | Modify 
License by Timur On July 17, 2010
Hi Mike, i would like to know, under which license such a tool could be created. could it be sold without any fees?
Reply | Email | Modify 
Re: License by Mike On July 17, 2010

Hi Timur,

Not sure what you are asking.  Do you mean creating a tool that uses Visio as a front end or creating an add-in for Visio that customizes it as a new tool?   I suspect you could do this, but you would need to somehow arrange with Microsoft an installation of Visio with your customer.  I suspect they have programs like this, but you would need to contact there business unit.  There are also other diagramming tools on the market such as GO.NET

Reply | Email | Modify 
Re: Re: License by Timur On July 18, 2010
Thanks for the fast answer. I'm looking for a free Node/Link - Diagramm component for creating nice to watch modell with custom grapfics (around 10 Node- and Linkstypes) The appwhich has addional features, so it's not just a modeleditor.

I figured there must be some standard approach to this.
Can you recommend a component, architecture or sample application (with code) for such a tool?
Reply | Email | Modify 
New Visio document in Web application C# by Peder On September 9, 2010
Hi!

I can open an existing Visio document from a Web application like this:

Document visioDoc = visio.Documents.Add("PathToExisting.vsd");

How do I open a new document to draw an organisation chart?

Thanks
Peder
Reply | Email | Modify 
Re: New Visio document in Web application C# by Peder On September 9, 2010
I got it:

Document visioDoc = visio.Documents.Add("");

So simple I could not get it!

Regards
Peder
Reply | Email | Modify 
Re: Re: New Visio document in Web application C# by Mike On September 9, 2010
Glad you figured it out, Peder.
Reply | Email | Modify 
How to catch events by Catalin On December 15, 2010
Hello, Really nice tutorial on how to use automation in visio. Anyway I need to catch shape events in visio in case a shape is moved, deleted or a connector is added/removed from it. Any ideea on how to do that? Thank you
Reply | Email | Modify 
WPF by joseph On February 15, 2011
Is it possible to do that with WPF? And if, how do I do that? If I choose the Microsoft Office Visio 14 Drawing Com Component it doesn´t appear in the toolbox. Any idea, how I can use the Visio functionality in a program with WPF? Thanks a lot!
Reply | Email | Modify 
Great Post, Very informative by Aspose On April 13, 2011
This is really a wonderfull post, I am sure you are going to like this product as well. You can Manipulate MS Visio Files on ASP.NET Web & Windows Applications. Here your are: http://www.aspose.com/categories/.net-components/aspose.diagram-for-.net/default.aspx
Reply | Email | Modify 
Hide More shapes menu in shapes window by Bala On May 31, 2011
Hi, How can we hide or close more shapes option in the shapes window Now am using visio 2010 programing if you have any idea, Please let me know.. Regards Balu
Reply | Email | Modify 
Re: Hide More shapes menu in shapes window by niraj On July 8, 2011
Visio type namespace error is comingho w to remove it
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.