2013-11-14 57 views
1

我一直在嘗試創建一個程序來處理使用VB.net在Microsoft Word中觸發的事件。我的最終目標是使用此程序來響應用戶關閉的Word,但是當我嘗試使用DocumentBeforeCloseDocumentBeforeSave時,它們似乎沒有觸發,但我有一個事件來處理NewDocument,並且它的工作方式應該如此。VB Word管理

這裏是我的代碼:

Imports Microsoft.Office.Interop 

Public Class Form1 

Private WithEvents oWord As Word.ApplicationClass 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    'Create a new instance of Word, make it visible, and activate it. 
    oWord = CreateObject("Word.Application") 
    oWord.Visible = True 
    oWord.Activate() 

    'Create a new document. 
    oWord.Documents.Add() 

    'Release the instance of Word and leave it running. 
    oWord = Nothing 

End Sub 

Private Sub oWord_ApplicationEvents2_Event_DocumentBeforeClose(Doc As Word.Document, ByRef Cancel As Boolean) Handles oWord.ApplicationEvents2_Event_DocumentBeforeClose 
    System.Windows.Forms.MessageBox.Show("The document is closing.") 
End Sub 


Private Sub oWord_ApplicationEvents2_Event_DocumentBeforeSave(Doc As Word.Document, ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles oWord.ApplicationEvents2_Event_DocumentBeforeSave 
    System.Windows.Forms.MessageBox.Show("The document is saving.") 
End Sub 
'Handler for the Microsoft Word NewDocument event. 
'The NewDocument event is fired when a new document is created. 

Private Sub oWord_ApplicationEvents2_Event_NewDocument(Doc As Word.Document) Handles oWord.ApplicationEvents2_Event_NewDocument 
    'Add some text to the new document. 
    With oWord.Selection 
     .TypeText("The ") 
     With .Font 
      .Bold = Word.WdConstants.wdToggle 
      .Italic = Word.WdConstants.wdToggle 
     End With 
     .TypeText("NewDocument ") 
     With .Font 
      .Bold = Word.WdConstants.wdToggle 
      .Italic = Word.WdConstants.wdToggle 
     End With 
     .TypeText("event handler inserted this text.") 
    End With 
End Sub 
End Class 

我有我的微軟Office互操作性和Microsoft Word對象庫的引用。

我在.ApplicationEvents2_Event_DocumentBeforeClose上找到了文檔,聲明它不是用於代碼的事件,但提供了一種聲明和使用它的方法,因此我不確定是否使用了錯誤的語法來使用或出錯一路走到一起。

回答

1

VB.NET

你可以指望通過一個定時器字的過程。這隻會工作以及計時器大於用戶打開和關閉其他文檔快..

Private m_wordProcessCount As Integer = 0 
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 
    Dim processCount As Integer = Process.GetProcessesByName("WinWord").Count() 
    If Not processCount < m_wordProcessCount Then 
     'a word process has been closed.. 
     doSomething() 
     'update our wordcount 
     m_wordProcessCount = processCount 
    End If 
End Sub 

Word的宏

您可以在Word中的關閉事件使用VBA ..

Private Sub Document_Close() 
    Dim strPath As String 
    strPath = Dir("C:\Program Files (x86)\SomeProgram\Program.exe") 
    'run the external exe 
    Shell strPath 
End Sub 

http://msdn.microsoft.com/en-us/library/office/aa211664(v=office.11).aspx