【问题标题】:Issue with async code when using WebView2 control inside VSTO Outlook plugin在 VSTO Outlook 插件中使用 WebView2 控件时出现异步代码问题
【发布时间】:2021-11-16 14:19:06
【问题描述】:

我想在 Outlook 的 VSTO 插件上使用最新的 Microsoft WebView2 控件 (Chromium)。 我无法将 WebView2 的异步接口与 VSTO Outlook.Inspector 和 Outlook.ItemEvents_10_Event 连接在一起,例如发送或关闭。

我想通过从 WebView2 控件调用 ExecuteScriptAsync 在 WebView2 上对这些事件执行一些 JS 脚本。

问题在于,例如 Send 事件被声明为 void ItemEvents_10_SendEventHandler(ref bool Cancel) 问题在于 ref 变量不能用于异步。

我需要将此异步代码包装到同步中以确定 ref Cancel 的结果,但我不知道。我最终遇到了死锁或来自 WebView2 控件的错误CoreWebView2 can only be accessed from the UI thread.

设置为 VS2019、Outlook PIA 15 和 WebView2 1.0.1020.30

【问题讨论】:

  • 显示更多代码,因此我们可以“使用”一些东西来描述您的代码。

标签: c# async-await vsto webview2


【解决方案1】:

在您的事件处理程序中,在等待异步方法返回时运行 Windows 消息循环

        MSG msg;
        while (PeekMessage(out msg, IntPtr.Zero, 0, 0, 1/*PM_REMOVE*/))
        {

            TranslateMessage(ref msg);
            DispatchMessage(ref msg);
            if (OnlyOnce) break;
        }

Win API 函数定义如下:

[StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MSG
        {
            public IntPtr hwnd;
            public uint message;
            public UIntPtr wParam;
            public IntPtr lParam;
            public int time;
            public POINT pt;
            public int lPrivate;
        }
        [DllImport("user32.dll")]
        static extern sbyte GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
        [DllImport("user32.dll")]
        static extern bool TranslateMessage([In] ref MSG lpMsg);
        [DllImport("user32.dll")]
        static extern IntPtr DispatchMessage([In] ref MSG lpmsg);
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);

【讨论】:

  • 感谢您的建议!
猜你喜欢
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多