|
|
|
|
|
Home
»
Office Interop
»
Drawing Visio Shapes in the Visio ActiveX Control using C# and .NET
|
|
|
Author Rank:
|
|
Total page views :
59661
|
|
Total downloads :
1666
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
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.
|
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.
|
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or
application via a range of API's. Learn More about our API connections.
|
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
|
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.
|
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
|
|
|
|
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|