在 Outlook 为 运行 时无法获取 Outlook.Application,直到非 Outlook window 出现在前台

Can't obtain Outlook.Application while Outlook is running until a non-Outlook window is in the foreground

Marshal.GetActiveObject("Outlook.Application") 在 Outlook 启动时抛出 Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE)) 并在 运行ning 期间继续,直到非 Outlook window 成为活动前台 window .

我运行正在 Windows10 版本 1803 内部版本 17134.523 上安装 Outlook 版本 1901 内部版本 11231.20130(这是我的本地计算机)。我观察到客户端机器不以这种方式运行。这发生在使用 .NET 4.5.2 和通过 NuGet 获得的 Microsoft.Office.Interop.Outlook 版本 15.0.4797.1003 的 WPF 应用程序中。

我反复运行下面的代码。如上所述,一旦最小化 Outlook 实例或将非 Outlook window 设置为前台,它将成功,但在此之前它可能会不断失败(下面的输出)。我尝试暂停约 20-30 秒,让 Outlook 有时间加载,但仍然得到相同的结果。

    // Detect that the active window is an Outlook window
    Outlook.Application app = null;
    // Optional: Wait for Outlook to load 20-30 sec using Thread.Sleep
    try
    {
        Debug.WriteLine("app");
        app = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
        Debug.WriteLine("got app");
    }
    catch (Exception exception)
    {
        Debug.WriteLine(exception.Message);
    }
    // Do things with app

虽然 Outlook 是 运行ning,但我希望看到:

app
got app

如果自 Outlook 启动以来将非 Outlook window 设置为前台(即不是资源管理器或检查器 window),则会发生这种情况。如果 Outlook 是 运行ning 并且一直在前台,我会看到:

app
Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))

作为摸索,当我注意到这种情况时,我尝试通过执行以下操作来 "boot up" 互操作:

bootApplication = new Microsoft.Office.Interop.Outlook.Application();

没有效果。任何输入都会被重视。谢谢!

不要在 Outlook 中使用 GetActiveObject - 它是单例,因此创建 Outlook.Application 对象的新实例将 return 指向现有实例的指针,如果它是已经 运行。