Success... but a couple questions...
Confused about the canQuit variable... Is this how the instantiate routine
should look? I never saw you setting canQuit to true. See how I set it in 3
places. It is declared globally.
Private Sub InstantiateOutlook()
Try
Dim olProcess As String = "Outlook.exe"
Dim query As New SelectQuery("SELECT Name FROM Win32_Process
WHERE name='" & olProcess & "'")
Dim searcher As New ManagementObjectSearcher(query)
Dim objectCollection As ManagementObjectCollection =
searcher.Get()
Dim collCount As Integer = objectCollection.Count
searcher.Dispose()
objectCollection.Dispose()
searcher = Nothing
objectCollection = Nothing
If collCount <> 0 Then
' Outlook already running, hook into the Outlook instance
objOutlook =
TryCast(Marshal.GetActiveObject("Outlook.Application"), Outlook.Application)
If objOutlook IsNot Nothing Then
canQuit = False
Else
canQuit = True
End If
Else
' Outlook not already running, start it
canQuit = True
Dim _app As New Outlook.ApplicationClass()
objOutlook = DirectCast(_app, Outlook.Application)
End If
Catch ex As System.Exception
MessageBox.Show(ex.Message)
End Try
End Sub
And now when I use my routine I am unclear how to use the canQuit variable.
If Outlook is already running, I simply don't want to exit it? I tried this,
and then exited the Outlook UI by hand, but Outlook still stays in memory.
How did you mean this canQuit should be used?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
Dim objNameSpace As Outlook.NameSpace
Dim objFolder As Outlook.MAPIFolder
Dim colItems As Outlook.Items
Dim objItem As Outlook.MailItem
Dim iterations As Integer
InstantiateOutlook()
objNameSpace = objOutlook.GetNamespace("MAPI")
objFolder =
objNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
objNameSpace.Logon()
colItems = objFolder.Items
For i = 1 To colItems.Count
iterations += 1
objItem = colItems.Item(i)
' whatever
Marshal.ReleaseComObject(objItem)
objItem = Nothing
If iterations = 50 Then Exit For
Next
If canQuit Then ' what to do here?
Marshal.ReleaseComObject(colItems)
Marshal.ReleaseComObject(objFolder)
Marshal.ReleaseComObject(objNameSpace)
objOutlook.Quit()
Marshal.ReleaseComObject(objOutlook)
GC.Collect()
GC.WaitForPendingFinalizers()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Try
End Sub