我不太确定是什么导致Visio无法响应还原,但您可以尝试使用“AddAdvise”方法:
[ComVisible(true)] public partial class Form1 : Form, Visio.IVisEventProc { public Form1() { InitializeComponent(); } Visio.Application app; bool initialised = false; private void button1_Click(object sender, EventArgs e) { init(); app.Documents.Add("C:\\test.vst"); // creates new document from template } void init() { if (!initialised) { // only initialise once app = new Visio.Application(); // app.BeforeDocumentClose += app_BeforeDocumentClose; app.EventList.AddAdvise(DocCloseEventCode, this, null, null); initialised = true; Application.DoEvents(); } } const short DocCloseEventCode = unchecked((short)Visio.VisEventCodes.visEvtDoc + (short)Visio.VisEventCodes.visEvtDel); object Visio.IVisEventProc.VisEventProc(short eventCode, object source, int eventID, int eventSeqNum, object subject,object moreInfo) { if (eventCode == DocCloseEventCode) app_BeforeDocumentClose(subject as Visio.Document); return null; } void app_BeforeDocumentClose(Visio.Document doc) { } }
要使用Nikolay的建议为多个事件提供完整的解决方案,这里是完整的代码,包括事件和(de)Visio应用程序的初始化,而不使用模板。 (请注意,消息框可能会在后台显示在Visio窗口后面。)
using System; using System.Runtime.InteropServices; using System.Windows.Forms; using Visio = Microsoft.Office.Interop.Visio; namespace VisioInteropTest { [ComVisible(true)] public partial class TestForm : Form, Visio.IVisEventProc { Visio.Application app; bool initialised = false; // all AddAdvise events: // https://msdn.microsoft.com/en-us/library/office/ff768620.aspx const short appCloseEventCode = (short)(Visio.VisEventCodes.visEvtApp | Visio.VisEventCodes.visEvtBeforeQuit); const short docCloseEventCode = (short)(Visio.VisEventCodes.visEvtDoc | Visio.VisEventCodes.visEvtDel); public TestForm() { InitializeComponent(); } private void visioButton_Click(object sender, EventArgs e) { if (init()) { app.Documents.Add(""); } } bool init() { if (!initialised) { app = new Visio.Application(); app.EventList.AddAdvise(appCloseEventCode, this, null, null); app.EventList.AddAdvise(docCloseEventCode, this, null, null); initialised = true; } return initialised; } object Visio.IVisEventProc.VisEventProc(short eventCode, object source, int eventID, int eventSeqNum, object subject, object moreInfo) { switch (eventCode) { case appCloseEventCode: app_BeforeAppClose((Visio.Application)subject); break; case docCloseEventCode: app_BeforeDocumentClose((Visio.Document)subject); break; } return null; } void app_BeforeAppClose(Visio.Application app) { initialised = false; MessageBox.Show("App closed"); } void app_BeforeDocumentClose(Visio.Document doc) { MessageBox.Show("Doc closed"); } } }