Share via


Obter e fazer logon em uma instância do Outlook

Este tópico mostra como obter um objeto Application que representa uma instância ativa do Outlook, se houver um em execução no computador local ou para criar uma nova instância do Outlook, fazer logon no perfil padrão e retornar essa instância do Outlook.

[!OBSERVAçãO] Helmut Obertanner fornecidos os exemplos de código a seguir. Antônio é um Microsoft Most Valuable Professional com experiência nas ferramentas de desenvolvimento do Microsoft Office no Microsoft Office Outlook e no Microsoft Visual Studio.

The following managed code samples are written in C# and Visual Basic. To run a .NET Framework managed code sample that needs to call into a Component Object Model (COM), you must use an interop assembly that defines and maps managed interfaces to the COM objects in the object model type library.

For Outlook, you can use Visual Studio and the Outlook Primary Interop Assembly (PIA). Before you run managed code samples for Outlook 2013, ensure that you have installed the Outlook 2013 PIA and have added a reference to the Microsoft Outlook 15.0 Object Library component in Visual Studio.

Você deve usar os exemplos de código a ThisAddIn seguir na classe de um suplemento do Outlook (usando ferramentas de desenvolvedor do Office para Visual Studio). The Application object in the code must be a trusted Outlook Application object provided by ThisAddIn.Globals. For more information about using the Outlook PIA to develop managed Outlook solutions, see the Outlook 2013 Primary Interop Assembly Reference on MSDN.

Os exemplos de código a seguir contêm o GetApplicationObject método da Sample classe, implementado como parte de um projeto de suplemento do Outlook. Cada projeto adiciona uma referência para o Outlook PIA, que se baseia no namespace Microsoft.Office.Interop.Outlook.

O GetApplicationObject método usa classes na Biblioteca de Classes .NET Framework para verificar e obter qualquer processo do Outlook em execução no computador local. Primeiro, ele usa o método GetProcessesByName da classe Process no namespace System.Diagnostics para obter uma matriz de componentes de processo no computador local que compartilham o nome do processo "OUTLOOK".

Para verificar se a matriz contém pelo menos um processo do Outlook, GetApplicationObject use o LINQ (Microsoft Language Integrated Query). A classe Enumerável no namespace System.Linq fornece um conjunto de métodos, incluindo o método Count, que implementam a interface genérica IEnumerable(T).

Como a classe Array implementa a interface GetApplicationObjectIEnumerable(T), pode aplicar o método Count à matriz retornada por GetProcessesByName para ver se há um processo do Outlook em execução. Se houver, GetApplicationObject usará o método GetActiveObject da classe Marshal no namespace System.Runtime.InteropServices para obter essa instância do Outlook e lançará esse objeto para um objeto do Outlook Application .

Se o Outlook não estiver em execução no computador local, GetApplicationObject criar uma nova instância do Outlook, usará o método Logon do objeto NameSpace para fazer logon no perfil padrão e retornará essa nova instância do Outlook.

Veja a seguir o exemplo de código do C#.

using System; 
using System.Diagnostics; 
using System.Linq; 
using System.Reflection; 
using System.Runtime.InteropServices; 
using Outlook = Microsoft.Office.Interop.Outlook; 
 
namespace OutlookAddIn1 
{ 
    class Sample 
    { 
        Outlook.Application GetApplicationObject() 
        { 
 
            Outlook.Application application = null; 
 
            // Check if there is an Outlook process running. 
            if (Process.GetProcessesByName("OUTLOOK").Count() > 0) 
            { 
 
                // If so, use the GetActiveObject method to obtain the process and cast it to an Application object. 
                application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application; 
            } 
            else 
            { 
 
                // If not, create a new instance of Outlook and log on to the default profile. 
                application = new Outlook.Application(); 
                Outlook.NameSpace nameSpace = application.GetNamespace("MAPI"); 
                nameSpace.Logon("", "", Missing.Value, Missing.Value); 
                nameSpace = null; 
            } 
 
            // Return the Outlook Application object. 
            return application; 
        } 
 
    } 
}

Veja a seguir o exemplo de código do Visual Basic.

Imports System.Diagnostics 
Imports System.Linq 
Imports System.Reflection 
Imports System.Runtime.InteropServices 
Imports Outlook = Microsoft.Office.Interop.Outlook 
 
Namespace OutlookAddIn2 
    Class Sample 
 
        Function GetApplicationObject() As Outlook.Application 
 
            Dim application As Outlook.Application 
 
            Check if there is an Outlook process running. 
            If Process.GetProcessesByName("OUTLOOK").Count() > 0 Then 
 
                ' If so, use the GetActiveObject method to obtain the process and cast it to an Application object. 
                application = DirectCast(Marshal.GetActiveObject("Outlook.Application"), Outlook.Application) 
            Else 
 
                ' If not, create a new instance of Outlook and log on to the default profile. 
                application = New Outlook.Application() 
                Dim ns As Outlook.NameSpace = application.GetNamespace("MAPI") 
                ns.Logon("", "", Missing.Value, Missing.Value) 
                ns = Nothing 
            End If 
 
            ' Return the Outlook Application object. 
            Return application 
        End Function 
 
    End Class 
End Namespace

Suporte e comentários

Tem dúvidas ou quer enviar comentários sobre o VBA para Office ou sobre esta documentação? Confira Suporte e comentários sobre o VBA para Office a fim de obter orientação sobre as maneiras pelas quais você pode receber suporte e fornecer comentários.