C#开发Visio例子
【实例简介】C#改变Visio阀门的开关
【实例截图】
【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Visio = Microsoft.Office.Interop.Visio;
using Microsoft.Office.Interop.Visio;
using System.IO;
using AxMicrosoft.Office.Interop.VisOcx;
using VisioLibrary;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private string basePath = @"图纸及模具\";
private string gStencileFileBasePath = @"图纸及模具\Stencils\";
#region Visio对象属性
[CLSCompliant(false)]
public Visio.Application VisApplication
{
get
{
return this.axDrawingControl1.Document.Application;
}
}
[CLSCompliant(false)]
public Visio.Window VisWindow
{
get
{
return this.axDrawingControl1.Document.Application.ActiveWindow;
}
}
[CLSCompliant(false)]
public Visio.Document VisDocument
{
get
{
return this.axDrawingControl1.Document.Application.ActiveDocument;
}
}
[CLSCompliant(false)]
public AxDrawingControl CtrlDrawing
{
get
{
return this.axDrawingControl1;
}
}
#endregion
private EventSink eventSink = null;
public Form1()
{
InitializeComponent();
basePath = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, basePath);
gStencileFileBasePath = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, gStencileFileBasePath);
}
private void InitSink()
{
eventSink = new EventSink();
eventSink.AddAdvise(VisApplication, VisDocument);
eventSink.OnShapeAdd += new VisioEventHandler(eventSink_OnShapeAdd);
eventSink.OnShapeDelete += new VisioEventHandler(eventSink_OnShapeDelete);
eventSink.OnMarkerEvent += new VisioEventHandler(eventSink_OnMarkerEvent);
}
void eventSink_OnShapeDelete(object sender, EventArgs e)
{
//bool isRedoOrUndo = VisApplication.IsUndoingOrRedoing;
//Shape shape = (Shape)sender;
//MessageBox.Show(shape.Name);
}
private void 打开Visio文档ToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = basePath + @"图纸4.vsd";
this.axDrawingControl1.Src = fileName;
this.axDrawingControl1.Src = "";
//打开模具列表操作
List<string> filePaths = GetFilePaths(gStencileFileBasePath);
foreach (string stencil in filePaths)
{
VisioUtility.OpenStencilRead(VisApplication.Documents, stencil);
}
}
void eventSink_OnMarkerEvent(object sender, EventArgs e)
{
var shape = sender as Shape;
string deviceType = VisioUtility.GetShapeCellValue(shape, "设备类型");
if (deviceType == "阀门")
{
string status = VisioUtility.GetShapeCellValue(shape, "状态");
string fomula = (status == "开") ? "关" : "开";
var fomulaString= VisioUtility.StringToFormulaForString(fomula);
shape.get_CellsSRC((short)VisSectionIndices.visSectionAction,
(short)VisRowIndices.visRowAction, (short)VisCellIndices.visActionMenu).Formula = fomulaString;
VisioUtility.SetShapeCellValue(shape, "状态", fomula);
status = VisioUtility.GetShapeCellValue(shape, "状态");
var backcolor = (status == "关") ? System.Drawing.Color.Black : System.Drawing.Color.White;
VisioUtility.SetShapeBackColor(shape, backcolor);
}
//MarketEventArgs args = e as MarketEventArgs;
//string ContextString = args.Argument;
//MessageBox.Show(ContextString);
}
void eventSink_OnShapeAdd(object sender, EventArgs e)
{
bool isRedoOrUndo = VisApplication.IsUndoingOrRedoing;
var shape = sender as Shape;
string deviceType = VisioUtility.GetShapeCellValue(shape, "设备类型");
if (deviceType.Contains("开关"))
{
VisioUtility.AddRightMouseAction(shape, "测试开关",
"RUNADDONWARGS(\"QueueMarkerEvent\",\"/Drawing=测试\")",
true, true, false, false, false, true);
}
else if (deviceType.Contains("阀门"))
{
string status = VisioUtility.GetShapeCellValue(shape, "状态");
var backcolor = (status == "关") ? System.Drawing.Color.Black : System.Drawing.Color.White;
VisioUtility.SetShapeBackColor(shape, backcolor);
VisioUtility.AddRightMouseAction(shape, status,
"RUNADDONWARGS(\"QueueMarkerEvent\",\"/Drawing=开或关\")",
true, true, false, false, false, true);
}
}
private List<string> GetFilePaths(string fileBasePath)
{
List<string> list = new List<string>();
string[] files = Directory.GetFiles(fileBasePath, "*.vss", SearchOption.TopDirectoryOnly);
foreach (string filePath in files)
{
list.Add(filePath);
}
return list;
}
private void axDrawingControl1_SelectionChanged(object sender, AxMicrosoft.Office.Interop.VisOcx.EVisOcx_SelectionChangedEvent e)
{
//foreach (Shape shape in e.window.Selection)
//{
// Console.WriteLine(shape.NameU);
//}
if (e.window.Selection.Count > 0)
{
Shape shape = e.window.Selection.Item16[1];
string value = VisioUtility.GetShapeCellValue(shape, "设备类型");
Console.WriteLine(value);
if (value.Contains("开关"))
{
var name = "生产厂家";
VisioUtility.SetShapeDefinition(shape, VisioUtility.ShapeField.Format,
name, "A厂家;B厂家;C厂家;D厂家");
//var NameValue = "ABC厂家";
//VisioUtility.SetShapeCellValue(shape, name, NameValue);
}
if (value == "阀门")
{
//string status = VisioUtility.GetShapeCellValue(shape, "状态");
//string fomula = (status == "开") ? "关" : "开";
//fomula = VisioUtility.StringToFormulaForString("=" + fomula);
//shape.get_CellsSRC((short)VisSectionIndices.visSectionAction,
// (short)VisRowIndices.visRowAction, 1).FormulaU = fomula;
}
}
}
private void axDrawingControl1_ShapeAdded(object sender, AxMicrosoft.Office.Interop.VisOcx.EVisOcx_ShapeAddedEvent e)
{
var shape = e.shape;
Console.WriteLine(shape.Name);
}
private void 另存为VisioToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "测试名称";
dlg.Filter = "Visio文件(*.vsd)|*.vsd|所有文件(*.*)|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.FileName.Trim() != string.Empty)
{
if (File.Exists(dlg.FileName))
{
File.Copy(basePath + @"图纸4.vsd", dlg.FileName, true);
}
else
{
File.Copy(basePath + @"图纸4.vsd", dlg.FileName);
}
}
}
}
private void 另存为PDFToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "";
dlg.Filter = "Pdf文件 (*.pdf)|*.pdf|AutoCAD 绘图 (*.dwg)|*.dwg|所有文件(*.*)|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.FileName.Trim() != string.Empty)
{
//VisApplication.ActivePage.Export(dlg.FileName);
VisDocument.ExportAsFixedFormat(Visio.VisFixedFormatTypes.visFixedFormatPDF,
dlg.FileName,
Visio.VisDocExIntent.visDocExIntentScreen,
Visio.VisPrintOutRange.visPrintAll,
1, VisDocument.Pages.Count, false, true, true, true, true,
System.Reflection.Missing.Value);
}
}
}
private void 保存JPGToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "";
dlg.Filter = "JPEG文件 (*.jpg)|*.jpg|所有文件(*.*)|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.FileName.Trim() != string.Empty)
{
VisApplication.ActivePage.Export(dlg.FileName);
}
}
}
private void 形状窗口ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdShapesWindow);
}
private void 属性数据窗口ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdCustProp);
}
private void 平移和缩放ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdPanZoom);
}
private void 显示隐藏标尺ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdViewRulers);
}
private void 大小和位置ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdSizePos);
}
private void 显示隐藏网格ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdViewGrid);
}
private void 设置形状窗口属性ToolStripMenuItem_Click(object sender, EventArgs e)
{
//使用Visio2007的操作
VisApplication.Settings.ShowShapeSearchPane = false;
VisApplication.Settings.EnableAutoConnect = false;
VisApplication.Settings.StencilBackgroundColor = 10070188;//vbGrayText
}
private void 获取设置对象属性值ToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void 打开关闭模具文档ToolStripMenuItem_Click(object sender, EventArgs e)
{
bool isOpen = VisioUtility.IsStencilOpened(VisApplication, "Label.vss");
if (isOpen)
{
VisioUtility.CloseAllStencileDocument(VisApplication);
}
else
{
//打开模具列表操作
List<string> filePaths = GetFilePaths(gStencileFileBasePath);
foreach (string stencil in filePaths)
{
VisApplication.Documents.OpenEx(stencil,
(short)VisOpenSaveArgs.visOpenRO |
(short)VisOpenSaveArgs.visAddDocked);
//VisioUtility.OpenStencilRead(VisApplication.Documents, stencil);
}
}
}
private void axDrawingControl1_MouseUpEvent(object sender, EVisOcx_MouseUpEvent eventData)
{
//if ((eventData.button == (int)VisKeyButtonFlags.visMouseRight) &&
// ((eventData.keyButtonState & (int)VisKeyButtonFlags.visKeyControl) == 0))
//{
// var clickedShape = VisioUtility.GetClickedShape(this.axDrawingControl1, eventData.x, eventData.y);
// //if (clickedShape != null)
// {
// eventData.cancelDefault = true;
// shapeShortcutMenu.Show(this, VisioUtility.MapVisioToWindows(axDrawingControl1, eventData.x, eventData.y));
// }
//}
}
private void axDrawingControl1_DocumentOpened(object sender, EVisOcx_DocumentOpenedEvent e)
{
InitSink();
}
private void 保存文档ToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "测试名称";
dlg.Filter = "Visio文件(*.vsd)|*.vsd|所有文件(*.*)|*.*";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if (dlg.FileName.Trim() != string.Empty)
{
this.axDrawingControl1.Document.SaveAs(dlg.FileName);
this.axDrawingControl1.Document.Saved = true;
}
}
}
private Page GetPage(string name)
{
Page result = null;
foreach (Page page in VisDocument.Pages)
{
if (page.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
result = page;
}
}
return result;
}
private void 动态绘制图形ToolStripMenuItem_Click(object sender, EventArgs e)
{
Page page = VisioUtility.GetPage(VisDocument, "馈线图");
double xPosition = page.PageSheet.get_CellsU("PageWidth").ResultIU;
double yPosition = page.PageSheet.get_CellsU("PageHeight").ResultIU;
Master master = VisioUtility.GetMasterItem(VisDocument, "建筑物");
if (master != null)
{
Shape tempShape = page.Drop(master, xPosition / 4, yPosition / 4);
tempShape.Text = "这个是从页面加的建筑物";
VisioUtility.SetShapeCharacterColor(tempShape, VisDefaultColors.visDarkRed);
VisioUtility.SetShapeBackColor(tempShape, System.Drawing.Color.Red);
}
var filePath = System.IO.Path.Combine(gStencileFileBasePath, "Switch.vss");
Document stencileDocument = VisioUtility.GetStencil(VisApplication.Documents, filePath);
master = VisioUtility.GetMasterItem(stencileDocument, "负荷开关");
if (master != null)
{
Shape tempShape = page.Drop(master, xPosition * 3 / 4, yPosition * 3 / 4);
tempShape.Text = "这个是从模具组加的设备";
VisioUtility.SetShapeLineColor(tempShape, VisDefaultColors.visDarkRed);
}
}
private void 列出模具属性ToolStripMenuItem_Click(object sender, EventArgs e)
{
var filePath = System.IO.Path.Combine(gStencileFileBasePath, "test.vss");
Document stencileDocument = VisioUtility.GetStencil(VisApplication.Documents, filePath);
var master = VisioUtility.GetMasterItem(stencileDocument, "测试模具");
if (master != null)
{
var shape = master.Shapes[1];//拿到Master对象下唯一的Shape对象
int rowCount = shape.get_RowCount((short)VisSectionIndices.visSectionProp);
Console.WriteLine(rowCount);
List<StencilInfo> list = new List<StencilInfo>();
for (short i = 0; i < rowCount; i++)
{
StencilInfo info = new StencilInfo();
info.Name = VisioUtility.GetShapeDefinition(shape, VisioUtility.ShapeField.Label, i);
info.Value = VisioUtility.GetShapeDefinition(shape, VisioUtility.ShapeField.Value, i);
list.Add(info);
}
var content = "";
foreach (StencilInfo info in list)
{
content += string.Format("{0}={1}", info.Name, info.Value);
//Console.WriteLine(content);
content += "\r\n";
}
FrmDisplay dlg = new FrmDisplay();
dlg.txtContent.Text = content;
dlg.ShowDialog();
}
}
private void 增加模具属性ToolStripMenuItem_Click(object sender, EventArgs e)
{
var filePath = System.IO.Path.Combine(gStencileFileBasePath, "test.vss");
VisApplication.Documents["test.vss"].Close();
var stencileDocument = VisioUtility.OpenStencilReadWrite(VisApplication.Documents, filePath);
var master = VisioUtility.GetMasterItem(stencileDocument, "测试模具");
if (master != null)
{
var shape = master.Shapes[1];//拿到Master对象下唯一的Shape对象
string deviceName = "Prop." + "设备类型";
string manufucture = "Prop." + "生产厂家";
var section = (short)VisSectionIndices.visSectionProp;
var tag = (short)(VisRowIndices.visRowProp);
if (shape.get_CellExists(deviceName, (short)VisExistsFlags.visExistsAnywhere) == 0)
{
short rowIndex = shape.AddNamedRow(section, "设备类型", tag);
VisioUtility.SetShapeDefinition(shape, VisioUtility.ShapeField.Label, rowIndex, "设备类型");
VisioUtility.SetShapeDefinition(shape, VisioUtility.ShapeField.Value, rowIndex, "测试模具A");
}
if (shape.get_CellExists(manufucture, (short)VisExistsFlags.visExistsAnywhere) == 0)
{
short rowIndex = shape.AddNamedRow(section, "生产厂家", tag);
VisioUtility.SetShapeDefinition(shape, VisioUtility.ShapeField.Label, rowIndex, "生产厂家");
VisioUtility.SetShapeDefinition(shape, VisioUtility.ShapeField.Value, rowIndex, "厂家A");
}
VisApplication.Documents["test.vss"].Save();
VisioUtility.OpenStencilRead(VisApplication.Documents, filePath);
}
}
private void 读取图纸关系ToolStripMenuItem_Click(object sender, EventArgs e)
{
Shape first = null;
var page = VisDocument.Pages["馈线图"];
foreach (Shape shape in page.Shapes)
{
string deviceType = VisioUtility.GetShapeCellValue(shape, "设备类型");
if (deviceType.Contains("变压器"))
{
first = shape;
}
}
List<int> list = new List<int>();
//遍历Connection关系
foreach (Visio.Connect connect in first.Connects)
{
Visio.Shape temp = connect.ToSheet;
if(temp.ID != first.ID)
{
list.Add(temp.ID);
}
temp = connect.FromSheet;
if (temp.ID != first.ID)
{
list.Add(temp.ID);
}
}
foreach (Visio.Connect connect in first.FromConnects)
{
Visio.Shape temp = connect.ToSheet;
if (temp.ID != first.ID)
{
list.Add(temp.ID);
}
temp = connect.FromSheet;
if (temp.ID != first.ID)
{
list.Add(temp.ID);
}
}
string content = string.Join(",", list.ToArray());
content += "\r\n";
foreach (int id in list)
{
Shape shp = page.Shapes.get_ItemFromID(Convert.ToInt16(id));
if (shp != null)
{
content += shp.Name + ",";
}
}
FrmDisplay dlg = new FrmDisplay();
dlg.txtContent.Text = content;
dlg.ShowDialog();
}
private void 打印图纸ToolStripMenuItem_Click(object sender, EventArgs e)
{
var page = VisDocument.Pages["馈线图"];
page.Document.PrintOut(VisPrintOutRange.visPrintAll, 1, 1, false, "", false,
page.Name, 1, false, false);
//page.Document.PrintOut(VisPrintOutRange.visPrintCurrentPage, 1, 1, false, "", false,
// page.Name, 1, false, false);
page.Document.PrintOut(VisPrintOutRange.visPrintSelection, 1,
1, false, "", false, page.Name, 1, false, false);
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdView50);
}
private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdView100);
}
private void 页面宽度ToolStripMenuItem_Click(object sender, EventArgs e)
{
VisApplication.DoCmd((short)VisUICmds.visCmdZoomPageWidth);
}
private void 设备查询ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.VisWindow.Selection.Count <= 0)
{
MessageBox.Show("请选择设备");
return;
}
List<DeviceInfo> list = new List<DeviceInfo>();
foreach (Shape shape in this.VisWindow.Selection)
{
string name = VisioUtility.GetShapeCellValue(shape, "名称");
string type = VisioUtility.GetShapeCellValue(shape, "设备类型");
string special = VisioUtility.GetShapeCellValue(shape, "规格型号");
DeviceInfo info = new DeviceInfo(name, type, special);
list.Add(info);
}
Dictionary<string, List<DeviceInfo>> dict =
new Dictionary<string,List<DeviceInfo>>();
foreach (DeviceInfo info in list)
{
if (dict.ContainsKey(info.DeviceType))
{
dict[info.DeviceType].Add(info);//添加对应的值
}
else
{
//初始化列表
List<DeviceInfo> tmpList = new List<DeviceInfo>();
tmpList.Add(info);
dict.Add(info.DeviceType, tmpList);
}
}
string content = "";
foreach(string key in dict.Keys)
{
List<DeviceInfo> tmpList = dict[key];
DeviceInfo info = tmpList[0];
if (info != null)
{
content += string.Format("设备类型:{0} \t\t 规格型号{1} \t\t数量:{2}",
info.DeviceType, info.SpecialType, tmpList.Count) + "\r\n";
}
}
FrmDisplay dlg = new FrmDisplay();
dlg.txtContent.Text = content;
dlg.ShowDialog();
}
private void 绘制统计资产栏目ToolStripMenuItem_Click(object sender, EventArgs e)
{
Visio.Page page = VisioLibrary.VisioUtility.GetPage(VisDocument, "背景");
VisApplication.ActiveWindow.Page = page;//设置当前的活动页面
double leftTopX = 0.6024; //左上角顶点X坐标
double leftTopY = 22.33;//左上角顶点Y坐标
double leftCellWidth = 1;//统计项单元格宽度
double rightCellWidth = 1;//统计内容单元格宽度
double cellHeight = 0.22;//单元格高度
string shapeTypeName = string.Empty;
//把原有的统计项先抹掉
if (VisioLibrary.VisioUtility.HasShapeInWindow(VisApplication.ActiveWindow))
{
VisApplication.ActiveWindow.SelectAll();
foreach (Visio.Shape shape in VisApplication.ActiveWindow.Selection)
{
if (shape.Data1 == "tongji")
{
shape.Delete();
}
}
VisApplication.ActiveWindow.DeselectAll();
}
//绘制统计框
for (int j = 0; j < 3; j++)
{
Visio.Shape shape = VisioLibrary.VisioUtility.DrawRectangeOnPage(VisApplication,
leftTopX, leftTopY - j * cellHeight,
leftTopX + leftCellWidth, leftTopY - (j + 1) * cellHeight);
VisioLibrary.VisioUtility.SetShapeCharacterSize(shape, "7 pt");
//第一个单元格用于放统计项名称
shape.NameU = "统计" + j;
shape.Text = "统计" + j;
shape.Data1 = "tongji";//用tongji来标识Data1这个属性只是为了在删除这些框的时候便于查找到
//绘制统计值
shape = VisioLibrary.VisioUtility.DrawRectangeOnPage(VisApplication,
leftTopX + leftCellWidth, leftTopY - j * cellHeight,
leftTopX + leftCellWidth + rightCellWidth,
leftTopY - (j + 1) * cellHeight);
shape.NameU = "统计" + j +"v";
shape.Text = j + "米";
shape.Data1 = "tongji";
VisioLibrary.VisioUtility.SetShapeCharacterSize(shape, "12 pt");
VisioUtility.SetShapeLineColor(shape, VisDefaultColors.visBlue);
}
}
}
public class DeviceInfo
{
public DeviceInfo(string name, string type, string special)
{
this.Name = name;
this.DeviceType = type;
this.SpecialType = special;
}
public string Name { get; set; }
public string DeviceType { get; set; }
public string SpecialType { get; set; }
}
}