2011-06-06 16 views
6

Tengo la siguiente tarea. Estoy escribiendo un complemento para Visio 2010 en C# en Studio 2010. Digamos que tengo un diagrama abierto. Y tengo una forma de cualquier tipo en este diagrama (intentemos administrar una forma para el comienzo). La pregunta es ¿cómo puedo leer las propiedades de esta forma? ¿Qué API debería usar?Cómo leer las propiedades de Shape en Visio

algoritmo básica:

  1. Scan abrió documento para formas
  2. Si hay formas en el documento, a continuación, devolver una matriz (o una lista) de todas formas (nulo se devuelve en caso de no haber formas en el documento actual)
  3. Ejecutar más formas matriz y leer cualquier propiedad para cada elemento (que sería bueno tener la oportunidad de escribir/modificar la propiedad)

(Código ejemplo sería en gran medida una ppreciated)

Respuesta

8

Supongo que por propiedades te refieres a Shape Data, que solía llamarse Propiedades personalizadas en la interfaz de usuario y todavía se conoce con ese nombre en la API.

Si no está familiarizado con ShapeSheet, primero debe ver una forma con propiedades personalizadas en ShapeSheet para ver cómo se definen las propiedades. Consulte "What happened to the ShapeSheet?" para obtener información sobre cómo abrir la Hoja de formas en Visio 2010.

El siguiente programa de ejemplo debe comenzar. Este ejemplo asume que tiene el Visio Primary Interop Assembly instalado en su PC y que ha incluido un árbitro en Microsoft.Office.Interop.Visio en su proyecto.

namespace VisioEventsExample 
{ 
    using System; 
    using Microsoft.Office.Interop.Visio; 

    class Program 
    { 
     public static void Main(string[] args) 
     { 
      // Open up one of Visio's sample drawings. 
      Application app = new Application(); 
      Document doc = app.Documents.Open(
       @"C:\Program Files\Microsoft Office\Office14\visio content\1033\ASTMGT_U.VST"); 

      // Get the first page in the sample drawing. 
      Page page = doc.Pages[1]; 

      // Start with the collection of shapes on the page and 
      // print the properties we find, 
      printProperties(page.Shapes); 
     } 

     /* This function will travel recursively through a collection of 
     * shapes and print the custom properties in each shape. 
     * 
     * The reason I don't simply look at the shapes in Page.Shapes is 
     * that when you use the Group command the shapes you group become 
     * child shapes of the group shape and are no longer one of the 
     * items in Page.Shapes. 
     * 
     * This function will not recursive into shapes which have a Master. 
     * This means that shapes which were created by dropping from stencils 
     * will have their properties printed but properties of child shapes 
     * inside them will be ignored. I do this because such properties are 
     * not typically shown to the user and are often used to implement 
     * features of the shapes such as data graphics. 
     * 
     * An alternative halting condition for the recursion which may be 
     * sensible for many drawing types would be to stop when you 
     * find a shape with custom properties. 
     */ 
     public static void printProperties(Shapes shapes) 
     { 
      // Look at each shape in the collection. 
      foreach (Shape shape in shapes) 
      {    
       // Use this index to look at each row in the properties 
       // section. 
       short iRow = (short) VisRowIndices.visRowFirst; 

       // While there are stil rows to look at. 
       while (shape.get_CellsSRCExists(
        (short) VisSectionIndices.visSectionProp, 
        iRow, 
        (short) VisCellIndices.visCustPropsValue, 
        (short) 0) != 0) 
       { 
        // Get the label and value of the current property. 
        string label = shape.get_CellsSRC(
          (short) VisSectionIndices.visSectionProp, 
          iRow, 
          (short) VisCellIndices.visCustPropsLabel 
         ).get_ResultStr(VisUnitCodes.visNoCast); 

        string value = shape.get_CellsSRC(
          (short) VisSectionIndices.visSectionProp, 
          iRow, 
          (short) VisCellIndices.visCustPropsValue 
         ).get_ResultStr(VisUnitCodes.visNoCast); 

        // Print the results. 
        Console.WriteLine(string.Format(
         "Shape={0} Label={1} Value={2}", 
         shape.Name, label, value)); 

        // Move to the next row in the properties section. 
        iRow++; 
       } 

       // Now look at child shapes in the collection. 
       if (shape.Master == null && shape.Shapes.Count > 0) 
        printProperties(shape.Shapes); 
      } 
     } 
    } 
} 
+0

Hola Pat Gracias por su detallada responder. Eso me dio algunas ideas. Me las arreglé para continuar con mi tarea con su ayuda y varios libros. Planeo trabajar estrechamente con Visio durante el siguiente mes o dos. ¿Puedo agregarlo a mis contactos en LinkedIn ya que puedo necesitar su ayuda y consejo? (He enviado una invitación) Gracias de nuevo. Dan –

+0

Daniil, si tiene preguntas relacionadas con el desarrollo de software, pregúnteles sobre el desbordamiento de la pila. Si necesita contactarme en privado, use mi dirección de correo electrónico en mi perfil. - Pat –

4

escribí a library that makes this a easier

Para recuperar las propiedades de varias formas:

var shapes = new[] {s1, s2}; 
var props = VA.CustomProperties.CustomPropertyHelper.GetCustomProperties(page, shapes); 

El valor de retorno almacenada en apoyos será una lista de diccionarios. Cada diccionario corresponde a las propiedades de las formas especificadas. Los nombres de las propiedades son las claves en el diccionario.

Para obtener la propiedad "Foo" para la primera forma ...

props[0]["Foo"] 

que recupera un objeto que contiene las fórmulas & Resultados para estos aspectos de una propiedad:

  • Calendario
  • Formato
  • invisible
  • Etiqueta
  • LANGID
  • Mensaje
  • SortKey
  • Tipo
  • Valor
  • Verificar
+0

Hola Saveenr. Aprecio tu voluntad de ayudarme. Muchas gracias. –

+0

Gran biblioteca. ¡Gracias! –

0

Para todos aquellos, que necesitarán ayuda código más tarde sobre esta cuestión:

... 
using Visio = Microsoft.Office.Interop.Visio; 

namespace RibbonCustomization 
{ 
    [ComVisible(true)] 
    public class Ribbon1 : Office.IRibbonExtensibility 
    { 

     public void ReadShapes(Microsoft.Office.Core.IRibbonControl control) 
     { 
     ExportElement exportElement; 
     ArrayList exportElements = new ArrayList(); 

     Visio.Document currentDocument = Globals.ThisAddIn.Application.ActiveDocument; 
     Visio.Pages Pages = currentDocument.Pages; 
     Visio.Shapes Shapes; 

     foreach(Visio.Page Page in Pages) 
     { 
      Shapes = Page.Shapes; 
      foreach (Visio.Shape Shape in Shapes) 
      { 
       exportElement = new ExportElement(); 
       exportElement.Name = Shape.Master.NameU; 
       exportElement.ID = Shape.ID;    
       exportElement.Text = Shape.Text; 
       ... 
       // and any other properties you'd like 

       exportElements.Add(exportElement); 
      } 
     } 
.... 
Cuestiones relacionadas