Microsoft office interop outlook
Отслеживание и получение количества непрочитанных сообщений в Microsoft Outlook: Справочник по C#
Очень часто бывает полезно организовать взаимодействие вашей программы с Microsoft Office (а также воспользоваться массой встроенных в него классов). При помощи сборок, поставляемых с продуктами Office, вы можете выполнять самые разнообразные операции, в том числе те, к которым пользователь, работавший ранее с программами этого пакета, уже привык. Рассмотрим взаимодействие с Outlook в контексте приложения .NET. Для реализации данной задачи используется объектная библиотека «Microsoft Word 14.0 Object Library».
Создайте проект «Windows Form» в «Microsoft Visual Studio», для этого запустите среду разработки и перейдите в меню Файл->Создать…->Проект. Выберете версию .Net Fraemwork и введите имя проекта.
Перейдите в «Обозреватель решений» и найдите группу «References» которая содержит все ссылки на внешние компоненты в проекте. Сделайте клик правой клавишей мыши по данной группе и выберете из появившегося контекстного меню, пункт «Добавить ссылку…».
У вас откроется окно «Менеджер ссылок – (имя вашего проекта)», в левой части данного окна вам будет предложено выбрать одну из категорий. Visual Studio предоставляет четыре группы для выбора.
«Сборки» — список всех компонентов платформы .NET Framework, ссылки на которые можно добавить.
«Решение» — список всех повторно используемых компонентов, созданных в локальных проектах.
«COM» — список всех COM-компонентов, ссылки на которые можно добавить.
«Обзор» — позволяет осуществлять поиск компонента в файловой системе.
Выберете группу «Сборки» и ее подгруппу «Расширения». В центральной части окна вам будет предложен список доступных библиотек для подключения к вашему проекту. Найдите в списке библиотеку «Microsoft.Office.Interop.Outlook» и поставьте галочку рядом с именем данной библиотеки. В нижней части окна нажмите кнопку «ОК».
После добавления библиотеки, в обозревателе решений у вас появится новый пункт «Microsoft.Office.Interop.Outlook». Для работы с добавленной ссылкой необходимо добавить следующее пространство имен с использованием директивы «using»:
- using Outlook = Microsoft.Office.Interop.Outlook; – указывается ссылка на использование типов в пространстве имен «Microsoft.Office.Interop.Outlook», так же создается псевдоним «Outlook», этого пространства имен.
Сделайте двойной клик левой клавишей мыши по свободному пространству главной формы, для создания обработчика событий «Load». В редакторе кода откроется файл кода главной формы, с установкой курсора в обработчике события «Form1_Load». В данном событии выполним поиск и подключение к запущенному экземпляру «Microsoft Outlook» или создадим новый, а так же создадим обработчик событий при поступлении нового письма. Полный листинг для вставки в данный метод представлен ниже:
Далее необходимо добавить метод обработки события при получении нового сообщения:
Так же необходимо в класс главной формы добавить следующую переменную:
Запустите ваш проект, нажав на клавишу «F5». У вас запустится главная форма в режиме ожидания нового письма. При поступлении нового письма вы увидите сообщение с количеством непрочитанных сообщений.
Microsoft office interop outlook
Outlook 2007 object model incorporates the CDO 1.21 library
The only real difference between the VSTO 2005 Outlook 2003 add-in and the add-ins in VSTO 2005 SE is that the add-in host item base class wraps the Outlook Application PIA object
VSTO does not add any functionality to the Outlook object model
VSTO does not create any host items or host controls
Outlook Add-ins
These differ from Excel and Word add-ins because they must be registered in the registry
This means you must use a Setup Project to install your add-in.
When you create an Outlook add-in a setup project is automatically created for you ??
Outlook add-ins do not support Smart Tags, Task Pane Customisation or Data Caching.
Security
The security requirements of Outlook add-ins match those of Excel and Word document-level customisation.
By default VSTO solutions are very secure and require Code Access Security (CAS)
The security model in Outlook 2003 was improved with an email security update to help protect users from email viruses
This security model (often referred to as the Outlook Object Model Guard) prevents access to certain members of the Outlook object model.
It automatically trusts all installed COM Add-ins provided that you access the outlook objects through the Outlook application object (ThisApplication)
If you create a new instance then calls are restricted
Use ThisApplication instead of creating a new instance of an Application object
When Outlook is used with Exchange Server administrators can specify that all VSTO add-ins be trusted because they can specify that the AddinLoader.dll be trusted.
If macro security is set to VeryHigh or High then the add-in must be signed with a certificate
The AddinLoader.dll that shipped with VSTO was not signed, but installing VSTO 2005 SE will replace it with a signed version.
The Outlook Shutdown Issue
The Outlook shutdown problem occurs when there are unreleased references to the Outlook objects in a COM add-in (implementing IDTExtensibility2) when the application is closed
Because there are still references to Outlook objects, the OnDisconnection method never gets called and Outlook doesn’t get closed properly
Even though the Outlook user interface might not be visible, Outlook is still running (task manager has outlook.exe)
VSTO helps address this issue by keeping track on the number of Inspectors and Explorers that are opened and closed
When no more windows are open in Outlook, it indicates that Outlook has closed and VSTO ensures that Outlook is shut down properly
It does this by unloading the application domain in which the add-ins were loaded and releasing the references to any COM objects
It is important to release though that you still might experience problems when Outlook closes if you are automating Outlook and you are create a running instance of Outlook without making it visible or opening any of its windows (if no Inspectors or Explorers are opened then VSTO cannot track them)
Events
The main difference between the NewMail and NewMailEx events is that with the NewMailEx you get information about each of the items based on its ID.
You should use the Shutdown event handlers rather than QuitEvent because the add-in is unloaded before this event is raised
VSTO Add-ins (Outlook specific)
Visual Studio 2005 introduced the first VSTO type add-in which was only available for Outlook 2003.
This add-in model allowed Microsoft to get some valuable feedback before modifying the add-in model slightly before releasing Visual Studio 2005 SE.
The most significant change was to remove the host item base class (that wrapped the application PIA and made the add-in version specific) and replace it with an unwrapped application PIA object as a field in the class.
It is extremely easy to migrate an old style Outlook add-in to the new Outlook VSTO model.
The original VSTO 2005 Outlook add-in projects are still available in Visual Studio versions meaning that there are 2 VSTO add-in project types for Outlook 2003.
2003 add-ins will be registered the way that Office 2003 expects and uses VSTO runtime v2 even if it is running in Office 2007.
Object Model
Outlook custom property pages
Application
Inspectors
Inspector
Outlook Item
Explorers
Explorer
Folder
Items
Folders
Namespace
ApplicationEvents_11_Events — contains all the events defined for Outlook 2007
Select Name dialog box — SelectNamesDialog.Display()
objNamespace.PickFolder()
Outlook Ribbon
Use the Context property of the Ribbon class to get the Outlook Inspector object for the window
The Context property returns an object that can be cast to an Outlook.Inspector object
Stores Collection
This represents all the stores in the current Outlook profile
Store Object
This represents a file that stores email messages and other items.
If you are using an Exchange Server, this file might be:
1) on a server in a public folder
2) on a local computer in a pst file
3) on a local computer in an offline folder file (ost)
Declaring Events
Here is an example of how to declare an event handler for the Application Startup event
Application.Quit
Inspector.Close
Inspector.Activate
Explorer.Activate
Explorer.Close
MailItem.Send
Item.Close
//After the initializations are finished for the open Explorerto put it in a sorted list and the Inspectors collec-
//tion is initialized, the event handlers are added for the NewExplorer, ExplorerClose, and NewInspector
//events.
The code in Listing6.15 shows the event handler for the Explorer.Closeevent. When Explorer.Close
fires, the module-level m_Exploreris assigned to ActiveExplorer. If that fails, and there are no open
Inspectors, the Teardown()procedure is called to release all Outlook objects. The code in Listings 6.15
and 6.16 is only needed if you aren’t using Explorerwrappers and aren’t using VSTO 2005 SE. Similar
code is used in the Explorerand Inspectorwrappers to handle the Closeevents.
Listing6.15
When a new Inspectoris opened, it’s checked to make sure it’s not a Note Inspector, and if not a
module level m_InspectorClassobject is instantiated as the new Inspectorfor event-handling pur-
poses as shown in Listing6.16.
Inspectorevents that are overloaded by Inspectormethods, such as Close, are handled not by
theInspectorobject but by the InspectorClassobject in C#. This also applies to other objects
where events are overloaded by methods with the same name.
When the Inspectorcloses, the Closeevent handler assigns ActiveInspectorto m_Inspector, and
if that fails and there are no open Explorers, the Teardown()procedure is called to release the Outlook
objects, as shown below. The code in Listing6.17 is used only if wrapper classes aren’t being used.