KeiStory

728x90
반응형

C# WebView2 설치여부에 따라 설치되도록 처리하기

 

WPF 에서 웹페이지를 보여줘야해서 WebView2 를 사용해 프로그램을 만들었습니다.

프로그램을 사용하는 사용자에게는 WebView2 runtime 이 설치되어있어야 동작이 가능합니다.

최신 Windows 인 경우 Update 를 통해 설치가 되지만 설치가 안된 경우가 있어

이를 처리하기 위해 WebView2 runtime 설치여부를 확인하고 설치하도록 해야 했습니다.

아래는 이를 위해 처리하는 방법을 알아봅니다.

 

아래 처럼 WPF 에서 WebView2 를 사용합니다.

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>

 

비하인드 코드 단에서는 CheckWebview2Runtime() 메서드를 통해 체크하고

InstallWebview2RuntimeAsync() 메서드를 통해 Webview2 를 설치합니다.

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());
            }
        }
    }
}

위대로 처리하면 설치여부를 확인하고 설치가 되어있지 않다면 설치 파일을 다운받고

설치를 진행하고 프로그램이 구동됩니다.



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

프로그램을 실행하게되면 Webview2 가 설치되있지 않은 경우

MicrosoftEdgeWebview2Setup.exe 파일을 다운받고 해당 파일을 실행되면서

Wpf.WebView2Test.exe.WebView2 폴더가 생성된걸 확인 할수 있습니다.

 

728x90

공유하기

facebook twitter kakaoTalk kakaostory naver band