728x90
728x170

WebView2 를 이번에 사용해서 프로그램을 만들었는데
프로그램을 사용하는 사용자에게는 WebView2 runtime 이 설치되어있어야 동작이 가능했습니다.
이를 처리하기위해 WebView2 runtime 설치여부를 확인하고 설치하도록 했습니다.

MainWindow.xaml

<Window
    x:Class="Wpf.WebView2Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:Wpf.WebView2Test"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:wpf="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">
    <Grid>
        <wpf:WebView2
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            Source="https://kjun.kr" />
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;

using Microsoft.Win32;

using Path = System.IO.Path;

namespace Wpf.WebView2Test
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            if (!CheckWebview2Runtime())
            {
                Task.Run(async () => await InstallWebview2RuntimeAsync()).Wait();
            }
        }

        /// <summary>
        /// WebView2 설치여부를 반환합니다.
        /// </summary>
        /// <returns></returns>
        public static bool CheckWebview2Runtime()
        {
            bool result = false;

            // 64비트 OS 인 경우
            if (Environment.Is64BitOperatingSystem)
            {
                string subKey = @"SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}";
                using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(subKey))
                {
                    // pv 는 버전을 의미합니다.
                    if (ndpKey != null && ndpKey.GetValue("pv") != null)
                    {
                        Debug.WriteLine($"64 bit version : {ndpKey.GetValue("pv")}");
                        result = true;
                    }
                    else
                    {
                        Debug.WriteLine("64 bit not installed");
                        result = false;
                    }
                }
            }
            // 32비트 OS 인 경우
            else
            {
                string subKey = @"SOFTWARE\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}";
                using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subKey))
                {
                    // pv 는 버전을 의미합니다.
                    if (ndpKey != null && ndpKey.GetValue("pv") != null)
                    {
                        Debug.WriteLine($"32 bit version : {ndpKey.GetValue("pv")}");
                        result = true;
                    }
                    else
                    {
                        Debug.WriteLine("32 bit not installed");
                        result = false;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// WebView2 runtime 을 다운받고 설치 합니다.
        /// </summary>
        /// <returns></returns>
        public static async Task InstallWebview2RuntimeAsync()
        {
            string? exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string setupfileName = Path.Combine(exePath ?? "", "MicrosoftEdgeWebview2Setup.exe");

            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    var result = await httpClient.GetAsync("https://go.microsoft.com/fwlink/p/?LinkId=2124703");
                    var message = result.EnsureSuccessStatusCode();

                    // setup 파일 다운로드
                    using (var stream = await result.Content.ReadAsStreamAsync())
                    {
                        using (var fs = new FileStream(setupfileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        {
                            await stream.CopyToAsync(fs);
                        }
                    }

                    if (File.Exists(setupfileName))
                    {
                        // 설치
                        await Process.Start(setupfileName, " /silent /install").WaitForExitAsync(); // .NET6
                        // Process.Start(appName, " /silent /install").WaitForExit(); // .Net FrameWork

                        // 설치 후 setup 파일 제거
                        //if (File.Exists(appName))
                        //{
                        //    File.Delete(appName);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

위대로 처리하면 설치여부를 확인하고 설치가 되어있지 않다면 설치 파일을 다운받고 설치를 진행하고 프로그램이 구동됩니다.

아래처럼 프로젝트를 빌드하면 아래 처럼 구성이 되지만

프로그램을 실행하면 MicrosoftEdgeWebview2Setup.exe 파일을 다운받고 실행되면서 Wpf.WebView2Test.exe.WebView2 폴더가 생성된걸 확인 할수 있습니다.



[Source]
https://github.com/kei-soft/KJunBlog/tree/master/Wpf.WebView2Test

728x90
그리드형
Posted by kjun
,