Win32 message loop using P/Invoke in C#

Background

I want to render some HTML inside a headless instance of the MS CoreWebView2 to a PNG file.
The approach has to work inside a “pure” .Net8.0 console application on windows
(e.g. <TargetFramework>net8.0-windows</TargetFramework>).

Here is a condensed code sample showing my current approach:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using Microsoft.Web.WebView2.Core;
using System.Diagnostics;
namespace UiThread
{
internal class Program
{
static async Task Main(string[] args)
{
var filePath = "C:\Temp\webViewImage.png";
var html = @"
<!DOCTYPE html>
<html lang=""en"">
<head>
<meta charset=""UTF-8"">
<meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
";
var imageStream = await CaptureImage(html, new Size(512, 512));
using (var fileStream = File.Create(filePath))
{
imageStream.CopyTo(fileStream);
}
// Open file with default program.
Process.Start("explorer", """ + filePath + """);
}
static Task<Stream> CaptureImage(string html, Size size)
{
var tcs = new TaskCompletionSource<Stream>();
var thread = new Thread(() =>
{
// A SynchronizationContext like WindowsFormsSynchronizationContext is required.
SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
if (SynchronizationContext.Current == null)
throw new InvalidOperationException("Failed to create STA synchronization context.");
SynchronizationContext.Current.Post(async (state) =>
{
try
{
var isComplete = new TaskCompletionSource<bool>();
var host = new HeadlessCoreWebView2(isComplete, size);
await host.CaptureImage(html);
await isComplete.Task;
tcs.SetResult(host.Result);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
finally
{
Application.ExitThread(); // Exit the windows message loop.
}
}, null);
// A windows event loop with a message pump is needed in order to run the WebView2.
Application.Run();
});
// The thread apartment state must be STA (Single-threaded apartment).
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
}
internal class HeadlessCoreWebView2
{
private const IntPtr HWND_MESSAGE = -3;
private Size size;
private TaskCompletionSource<bool> tcs;
private CoreWebView2Controller? controller;
private TaskCompletionSource<bool> isInitialized = new TaskCompletionSource<bool>();
private Stream? result;
public HeadlessCoreWebView2(TaskCompletionSource<bool> tcs, Size size)
{
this.size = size;
this.tcs = tcs;
InitializeAsync();
}
public Stream Result
{
get
{
return result ?? new MemoryStream();
}
}
public async Task CaptureImage(string html)
{
await isInitialized.Task;
if (controller == null)
throw new ArgumentNullException();
controller.CoreWebView2.NavigateToString(html);
}
protected async void InitializeAsync()
{
var environment = await CoreWebView2Environment.CreateAsync(userDataFolder: null);
controller = await environment.CreateCoreWebView2ControllerAsync(HWND_MESSAGE);
controller.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded; ;
// Can be used to ensure, that the webview is initialized.
isInitialized.SetResult(true);
}
private async void CoreWebView2_DOMContentLoaded(object? sender, CoreWebView2DOMContentLoadedEventArgs e)
{
await RenderImage();
tcs?.SetResult(true);
}
private async Task<Stream> RenderImage()
{
if (controller == null)
throw new ArgumentNullException();
// Resize if needed.
if (controller.Bounds.Width != size.Width || controller.Bounds.Height != size.Height)
controller.Bounds = new Rectangle(Point.Empty, size);
var ms = new MemoryStream();
await controller.CoreWebView2.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, ms);
ms.Seek(0, SeekOrigin.Begin);
result = ms;
return ms;
}
}
}
</code>
<code>using Microsoft.Web.WebView2.Core; using System.Diagnostics; namespace UiThread { internal class Program { static async Task Main(string[] args) { var filePath = "C:\Temp\webViewImage.png"; var html = @" <!DOCTYPE html> <html lang=""en""> <head> <meta charset=""UTF-8""> <meta name=""viewport"" content=""width=device-width, initial-scale=1.0""> <title>Hello World</title> </head> <body> <h1>Hello World</h1> </body> </html> "; var imageStream = await CaptureImage(html, new Size(512, 512)); using (var fileStream = File.Create(filePath)) { imageStream.CopyTo(fileStream); } // Open file with default program. Process.Start("explorer", """ + filePath + """); } static Task<Stream> CaptureImage(string html, Size size) { var tcs = new TaskCompletionSource<Stream>(); var thread = new Thread(() => { // A SynchronizationContext like WindowsFormsSynchronizationContext is required. SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); if (SynchronizationContext.Current == null) throw new InvalidOperationException("Failed to create STA synchronization context."); SynchronizationContext.Current.Post(async (state) => { try { var isComplete = new TaskCompletionSource<bool>(); var host = new HeadlessCoreWebView2(isComplete, size); await host.CaptureImage(html); await isComplete.Task; tcs.SetResult(host.Result); } catch (Exception ex) { tcs.SetException(ex); } finally { Application.ExitThread(); // Exit the windows message loop. } }, null); // A windows event loop with a message pump is needed in order to run the WebView2. Application.Run(); }); // The thread apartment state must be STA (Single-threaded apartment). thread.SetApartmentState(ApartmentState.STA); thread.Start(); return tcs.Task; } } internal class HeadlessCoreWebView2 { private const IntPtr HWND_MESSAGE = -3; private Size size; private TaskCompletionSource<bool> tcs; private CoreWebView2Controller? controller; private TaskCompletionSource<bool> isInitialized = new TaskCompletionSource<bool>(); private Stream? result; public HeadlessCoreWebView2(TaskCompletionSource<bool> tcs, Size size) { this.size = size; this.tcs = tcs; InitializeAsync(); } public Stream Result { get { return result ?? new MemoryStream(); } } public async Task CaptureImage(string html) { await isInitialized.Task; if (controller == null) throw new ArgumentNullException(); controller.CoreWebView2.NavigateToString(html); } protected async void InitializeAsync() { var environment = await CoreWebView2Environment.CreateAsync(userDataFolder: null); controller = await environment.CreateCoreWebView2ControllerAsync(HWND_MESSAGE); controller.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded; ; // Can be used to ensure, that the webview is initialized. isInitialized.SetResult(true); } private async void CoreWebView2_DOMContentLoaded(object? sender, CoreWebView2DOMContentLoadedEventArgs e) { await RenderImage(); tcs?.SetResult(true); } private async Task<Stream> RenderImage() { if (controller == null) throw new ArgumentNullException(); // Resize if needed. if (controller.Bounds.Width != size.Width || controller.Bounds.Height != size.Height) controller.Bounds = new Rectangle(Point.Empty, size); var ms = new MemoryStream(); await controller.CoreWebView2.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, ms); ms.Seek(0, SeekOrigin.Begin); result = ms; return ms; } } } </code>
using Microsoft.Web.WebView2.Core;
using System.Diagnostics;

namespace UiThread
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var filePath = "C:\Temp\webViewImage.png";

            var html = @"
            <!DOCTYPE html>
            <html lang=""en"">
            <head>
                <meta charset=""UTF-8"">
                <meta name=""viewport"" content=""width=device-width, initial-scale=1.0"">
                <title>Hello World</title>
            </head>
            <body>
                <h1>Hello World</h1>
            </body>
            </html>
            ";

            var imageStream = await CaptureImage(html, new Size(512, 512));
            using (var fileStream = File.Create(filePath))
            {
                imageStream.CopyTo(fileStream);
            }

            // Open file with default program.
            Process.Start("explorer", """ + filePath + """);
        }

        static Task<Stream> CaptureImage(string html, Size size)
        {
            var tcs = new TaskCompletionSource<Stream>();

            var thread = new Thread(() =>
            {
                // A SynchronizationContext like WindowsFormsSynchronizationContext is required.
                SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
                if (SynchronizationContext.Current == null)
                    throw new InvalidOperationException("Failed to create STA synchronization context.");


                SynchronizationContext.Current.Post(async (state) =>
                {
                    try
                    {
                        var isComplete = new TaskCompletionSource<bool>();

                        var host = new HeadlessCoreWebView2(isComplete, size);
                        await host.CaptureImage(html);

                        await isComplete.Task;

                        tcs.SetResult(host.Result);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                    finally
                    {
                        Application.ExitThread(); // Exit the windows message loop.
                    }
                }, null);

                // A windows event loop with a message pump is needed in order to run the WebView2.
                Application.Run();
            });

            // The thread apartment state must be STA (Single-threaded apartment).
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();

            return tcs.Task;
        }
    }

    internal class HeadlessCoreWebView2
    {
        private const IntPtr HWND_MESSAGE = -3;
        private Size size;
        private TaskCompletionSource<bool> tcs;
        private CoreWebView2Controller? controller;
        private TaskCompletionSource<bool> isInitialized = new TaskCompletionSource<bool>();
        private Stream? result;

        public HeadlessCoreWebView2(TaskCompletionSource<bool> tcs, Size size)
        {
            this.size = size;
            this.tcs = tcs;

            InitializeAsync();
        }

        public Stream Result
        {
            get
            {
                return result ?? new MemoryStream();
            }
        }

        public async Task CaptureImage(string html)
        {
            await isInitialized.Task;

            if (controller == null)
                throw new ArgumentNullException();

            controller.CoreWebView2.NavigateToString(html);
        }

        protected async void InitializeAsync()
        {
            var environment = await CoreWebView2Environment.CreateAsync(userDataFolder: null);

            controller = await environment.CreateCoreWebView2ControllerAsync(HWND_MESSAGE);
            controller.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded; ;

            // Can be used to ensure, that the webview is initialized.
            isInitialized.SetResult(true);
        }

        private async void CoreWebView2_DOMContentLoaded(object? sender, CoreWebView2DOMContentLoadedEventArgs e)
        {
            await RenderImage();
            tcs?.SetResult(true);
        }

        private async Task<Stream> RenderImage()
        {
            if (controller == null)
                throw new ArgumentNullException();

            // Resize if needed.
            if (controller.Bounds.Width != size.Width || controller.Bounds.Height != size.Height)
                controller.Bounds = new Rectangle(Point.Empty, size);

            var ms = new MemoryStream();
            await controller.CoreWebView2.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, ms);
            ms.Seek(0, SeekOrigin.Begin);
            result = ms;
            return ms;
        }
    }
}

Problem

The problem with the code above is that it requires me to enable <UseWindowsForms>true</UseWindowsForms> inside the .csproj.
However I have the requirement to neither use UseWindowsForms or UseWPF.

The root problem is that the CoreWebview2 requires a UI Thread / message loop in order to properly function.

Question

How can the behaviour of Application.Run() and WindowsFormsSynchronizationContext from WinForms be replicated, using only P/Invoke?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật