Friday, November 11, 2011

Application Events


Application Events

Application-level events are most useful when you write code for an Outlook COM Add-in. You cannot respond to application-level events in VBScript code behind an Outlook form.

ItemSend

The ItemSend event occurs when an item is sent either because a user clicked the Send button on the item or because code causes an item to be sent. Typically the Application_ItemSend event occurs after the form-level Item_Send event and before the form-level Item_Write and Item_Close events. You should apply user-interface elements such as alert and dialog boxes with care in the ItemSend event. If you use the Cancel argument to cancel sending the item and the item has already been sent from an openInspector, the Inspector will remain in its previously displayed state. The item's Inspector will not close as it normally would when the Send button is clicked. The following example unobtrusively strips all attachments from outgoing mail messages:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim oAttach As Outlook.Attachment
    If Item.Attachments.Count And Item.MessageClass = "IPM.Note" Then
        Do Until Item.Attachments.Count = 0
            Set oAttach = Item.Attachments.Item(1)
            oAttach.Delete
        Loop
    End If
End Sub
The example above assumes that you are writing code directly to the explicit Application object in VBA. If you are writing a COM Add-in or using an event handler to instantiate an Outlook Application object that has been declared using WithEvents, the name of the Application object will differ but the code will remain the same.

NewMail

The NewMail event occurs when an item arrives in the Inbox of the current logged-on user. The NewMail event will not occur if an item arrives in the mailbox of a user for whom the logged-on user has delegate permissions. NewMail is a generic event that notifies you that mail has arrived in the Inbox. Unlike the ItemSend event, it does not pass an Item object representing the item or items that have arrived in the Inbox. If you want to raise an event for the arrival of a specific item in a folder, you should declare an Items collection object using WithEvents. Assign the Items collection object to the Items property of the folder that you want to monitor, and then write an event procedure for the ItemAdd event of the Items collection object. If the Explorer window is minimized, the following NewMail example causes the Explorer window to display with a normal window state.
Private Sub Application_NewMail()
    Dim olExplorer As Outlook.Explorer
    Dim olFolder As Outlook.MAPIFolder
    Set olFolder = _
      Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
    Set olExplorer = Application.ActiveExplorer
    If olExplorer.WindowState = olMinimized Then
        If olExplorer.CurrentFolder <> olFolder Then
            olExplorer.CurrentFolder = olFolder
        End If
        olExplorer.WindowState = olNormalWindow
        olExplorer.Display
        olExplorer.Activate
    End If
End Sub

OptionsPagesAdd

OptionsPagesAdd is the one event in the Outlook Object Model that appears at first examination to be misnamed. This event occurs after a user selects the Options command on the Tools menu of the Outlook Explorer and before the Tools Options dialog box actually displays. Consequently, you may prefer to think of the OptionsPagesAdd event as the BeforeOptionsPagesAdd event. From the perspective of the Application object, the OptionsPagesAdd event refers to the property pages of the Tools Options dialog box. You can use this event to add custom property pages to the Tools Options dialog box. Previous versions of Outlook required complex C++ coding to add property pages to this dialog box. See Chapter 14 for a complete example of how to create an ActiveX control and use this control as a property page that stores and retrieves settings from the Windows registry.
Figure 9-7 illustrates a property page with the caption Sample Page that has been added to the Tools Options dialog box. Be aware that creating an Outlook property page requires a complete understanding of how to create ActiveX controls and how to read and save registry values. Typically, you will want to use the Windows registry to preserve user settings on controls in your property page.
The Programmatic ID of the ActiveX control that contains the controls on the property page is PPE.SamplePage. The Programmatic ID is also known as a ProgID and results from the combination of ProjectName.ClassName in the ActiveX control project that implements the property page. The syntax for using the Add method of the PropertyPages collection object is as follows:
Private Sub Application_OptionsPagesAdd(ByVal Pages As PropertyPages)
    Pages.Add "ProgID", Caption
End Sub
Figure 9.7 - The Sample Page property page is added to the Tools Options dialog box
Although alternative syntaxes are proposed for the PropertyPages Add method in the Microsoft Outlook Visual Basic Reference, the use of the Programmatic ID and the Caption will provide the most trouble-free coding practice. Be aware that if you use the ProgID argument with the Add method, the Caption argument is mandatory rather than optional. If you omit the Caption argument, Outlook will raise an internal error. Here is a one-line example of using the OptionsPagesAdd event to add a property page with a caption of Sample Page to the property pages in the Outlook Tools Options dialog box. The ActiveX control that implements the property page has been compiled so that its ProgID is PPE.SamplePage. The actual code that makes this property page behave as expected is part of the SamplePage ActiveX control.
Private Sub Application_OptionsPagesAdd(ByVal Pages As PropertyPages)
    Pages.Add "PPE.SamplePage", "Sample Page"
End Sub

Quit

The Application Quit event takes place when you exit Outlook. This event provides a location for you to clean up any objects that you have created in the Startup event. It is good programming practice to set any global object variables you have created to Nothing in the Quit event. The following code example illustrates this technique.
Private Sub Application_Quit()
    On Error Resume Next
    Set objNS = Nothing
    Set colExpl = Nothing
    Set colInsp = Nothing
    Set objExpl = Nothing
    Set objInsp = Nothing
End Sub

Reminder

The Reminder event occurs immediately before the reminder for an item is displayed. Outlook passes a generic Item object to the Reminder event procedure. If you want to determine the type of item for which the reminder is going to be displayed, examine the Item's Class property to determine the specific Outlook item type.
Private Sub Application_Reminder(ByVal Item As Object)
    Select Case Item.Class
        Case olMail
        MsgBox "You are about to receive a message reminder.", _
            vbInformation
        Case olAppointment
        MsgBox "You are about to receive an appointment reminder.", _
            vbInformation
        Case olTask
        MsgBox "You are about to receive a task reminder.", vbInformation
    End Select
End Sub

Startup

The Startup event fires when Outlook starts and after any Exchange or COM Add-ins have been loaded. Consequently, you can use the COMAddIns collection object to determine which COM Add-ins have been loaded on startup for the Outlook Application object. The Startup event is also the place where you'll want to create instances of other global object variables that you've declared using the WithEvents keyword. Object variables that are leading candidates for instantiation in the Startup event are the Inspectors collection object, the Explorers collection object, and the Items collection object for any folders where you want to write event procedure code when an item is added, changed, or removed in a specified folder.
The following example adds a command button to the Standard toolbar of the Outlook Explorer. Outlook 97 and Outlook 98 required C++ coding to achieve the same result. This toolbar button opens the While You Were Out template located in the file system.
Private Sub Application_Startup()
    Dim objCB As Office.CommandBar
    Dim objCBB As Office.CommandBarButton  
    Set objCB = Application.ActiveExplorer.CommandBars("Standard")
    Set objCBB = objCB.Controls.Add(msoControlButton)
    With objCBB
        .TooltipText = "Open While You Were Out Form"
        .Style = msoButtonIcon
        .FaceId = 1757
        .OnAction = "cmdWhile_Click"
    End With
End Sub

'This OnAction procedure must reside in module-level code
'rather than in ThisOutlookSession
Sub cmdWhile_Click()
    Dim objMsg As Outlook.MailItem
    Dim objInsp As Outlook.Inspector
    Set objMsg = Application.CreateItemFromTemplate _
        ("C:\ My Documents\while you were out.oft")
    Set objInsp = objMsg.GetInspector
    objMsg.Display
    'You must display the message before you set WindowState
    objInsp.WindowState = olNormalWindow
End Sub

New Application Events in Outlook 2002

The following events are new to Outlook 2002. The AdvancedSearchComplete and AdvancedSearchStopped events are critical to the functioning of programmatic search using the AdvancedSearch method of the Application object.

AdvancedSearchComplete

The AdvancedSearchComplete event occurs when the AdvancedSearch method has completed. Use this event to determine when a programmatic search has finished or to start a new procedure upon the completion of the search. The following example displays the Subject for each Results item in the Immediate window when the search is complete:
Private Sub objOutlook_AdvancedSearchComplete _
    (ByVal SearchObject As Search)
    Dim colResults As Results
    Set colResults = SearchObject.Results
    For Each objItem In colResults
        Debug.Print objItem.Subject
    Next
End Sub

AdvancedSearchStopped

The AdvancedSearchStopped event occurs when the Stop method is called on a Search object. If you call the Stop method on a Search object, the Results collection object might not contain complete results for the search.
Both the AdvancedSearchComplete event and the AdvancedSearchStopped event will fire only if the AdvancedSearch method is called programmatically. These events do not occur for a search that executes when a user invokes the Advanced Find dialog box in the Outlook user interface.

MapiLogonComplete

The MapiLogonComplete event occurs after the Application Startup event. When MapiLogonComplete occurs, it means that a valid MAPI session object has been created and that you have full access to all the objects, events, and properties in the Outlook Object Model.

No comments:

Post a Comment