Avalonia学习(十七)-CEF

今天开始继续Avalonia练习。

本节:CefNet

1.引入

CefNet.Avalonia.Eleven

2.项目引入

Program中加入

using Avalonia;
using Avalonia.ReactiveUI;
using Avalonia.Threading;
using CefNet;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace CefAvalonia
{
    internal sealed class Program
    {
        internal static CefAppImpl? app;
        private static DispatcherTimer? messagePump;
        private const int messagePumpDelay = 10;
        // Initialization code. Don't use any Avalonia, third-party APIs or any
        // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
        // yet and stuff might break.
        [STAThread]
        public static void Main(string[] args)
        {
            string cefPath = GetProjectPath(PlatformInfo.IsMacOS);
            bool externalMessagePump = args.Contains("--external-message-pump");

            if (PlatformInfo.IsMacOS)
            {
                externalMessagePump = true;
            }

            var settings = new CefSettings();
            settings.MultiThreadedMessageLoop = !externalMessagePump;
            settings.ExternalMessagePump = externalMessagePump;
            settings.NoSandbox = true;
            settings.WindowlessRenderingEnabled = true;
            settings.LocalesDirPath = Path.Combine(cefPath, PlatformInfo.IsMacOS ? "Resources" : "locales");
            settings.ResourcesDirPath = Path.Combine(cefPath, PlatformInfo.IsMacOS ? "Resources" : "");
            settings.LogSeverity = CefLogSeverity.Warning;
            settings.UncaughtExceptionStackSize = 8;

            App.FrameworkInitialized += App_FrameworkInitialized;
            App.FrameworkShutdown += App_FrameworkShutdown;

            app = new CefAppImpl();
            app.ScheduleMessagePumpWorkCallback = OnScheduleMessagePumpWork;
            app.Initialize(cefPath, settings);
            BuildAvaloniaApp()
                .StartWithClassicDesktopLifetime(args);
        }
        private static string GetProjectPath(bool isMacOS)
        {
            return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cefnet", "Release", isMacOS ? Path.Combine("cefclient.app", "Contents", "Frameworks", "Chromium Embedded Framework.framework") : "");
        }
        private static void App_FrameworkInitialized(object? sender, EventArgs e)
        {
            if (CefNetApplication.Instance.UsesExternalMessageLoop)
            {
                messagePump = new DispatcherTimer(TimeSpan.FromMilliseconds(messagePumpDelay), DispatcherPriority.Normal, (s, e) =>
                {
                    CefApi.DoMessageLoopWork();
                    Dispatcher.UIThread.RunJobs();
                });
                messagePump.Start();
            }
        }
        private static void App_FrameworkShutdown(object? sender, EventArgs e)
        {
            messagePump?.Stop();
        }

        private static async void OnScheduleMessagePumpWork(long delayMs)
        {
            await Task.Delay((int)delayMs);
            Dispatcher.UIThread.Post(CefApi.DoMessageLoopWork);
        }

        // Avalonia configuration, don't remove; also used by visual designer.
        public static AppBuilder BuildAvaloniaApp()
            => AppBuilder.Configure<App>()
                .UsePlatformDetect()
                .WithInterFont()
                .LogToTrace()
                .UseReactiveUI();
    }
}

APP中加入

using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using CefAvalonia.ViewModels;
using CefAvalonia.Views;
using System;

namespace CefAvalonia
{
    public partial class App : Application
    {
        public static event EventHandler? FrameworkInitialized;
        public static event EventHandler? FrameworkShutdown;
        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
        }

        public override void OnFrameworkInitializationCompleted()
        {
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                desktop.MainWindow = new MainWindow
                {
                    DataContext = new MainWindowViewModel(),
                };
            }

            base.OnFrameworkInitializationCompleted();
        }
    }
}

添加一个实现处理类

using CefNet;
using System;
using System.Runtime.InteropServices;

namespace CefAvalonia
{
    internal class CefAppImpl:CefNetApplication
    {
        protected override void OnBeforeCommandLineProcessing(string processType, CefCommandLine commandLine)
        {
            base.OnBeforeCommandLineProcessing(processType, commandLine);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                commandLine.AppendSwitch("no-zygote");
                commandLine.AppendSwitch("no-sandbox");
            }
        }
        public Action<long> ScheduleMessagePumpWorkCallback { get; set; }

        protected override void OnScheduleMessagePumpWork(long delayMs)
        {
            ScheduleMessagePumpWorkCallback(delayMs);
        }
    }
}

窗口后台

using Avalonia.Controls;
using CefNet.Avalonia;


namespace CefAvalonia.Views
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            WebView webview = new() { Focusable = true };
            Content = webview;

            webview.BrowserCreated += (s, e) => webview.Navigate("https://www.baidu.com");

            webview.DocumentTitleChanged += (s, e) => Title = e.Title;

            Closing += (s, e) => Program.app?.Shutdown();
        }
    }
}

最后,下载对应的库

CEF Automated Builds (spotifycdn.com)

运行效果

Avalonia是一个**跨平台的UI框架,用于创建桌面应用程序**。 以下是一些关于Avalonia的基本信息和学习资源: 1. **什么是Avalonia?**:Avalonia是一个基于WPF XAML的开源UI框架,它允许开发者使用.NET构建跨平台的桌面应用程序。Avalonia支持多种操作系统,包括Windows、Linux和macOS。 2. **准备工作**:在开始使用Avalonia之前,你需要安装相应的开发环境,并配置项目。这通常包括安装.NET SDK和Avalonia工具包。 3. **创建第一个Avalonia应用程序**:你可以通过官方文档或相关教程来创建你的第一个Avalonia应用,这将帮助你理解基本的应用程序结构和开发流程。 4. **XAML基础**:XAML是一种用于定义用户界面的语言,你可以学习如何使用XAML来创建界面布局和实现数据绑定。 5. **控件和样式**:Avalonia提供了丰富的控件库,你可以学习如何使用这些控件以及如何通过样式和模板来自定义它们的外观。 6. **MVVM模式**:MVVM(Model-View-ViewModel)是一种设计模式,用于分离应用程序的业务逻辑和界面表示。学习MVVM将有助于你构建可维护和可测试的应用程序。 7. **导航和多窗口**:了解如何在Avalonia中进行窗口导航和管理多个窗口,这对于构建复杂的桌面应用程序非常重要。 8. **打包和发布应用程序**:最后,你需要学习如何将你的Avalonia应用程序打包和发布,以便用户可以在他们的计算机上安装和使用你的应用。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值