Browse Source

完成提取网页图标、完善新窗口弹出

CaptB 4 months ago
parent
commit
1807e73082
6 changed files with 132 additions and 28 deletions
  1. 15 0
      App.config
  2. 12 0
      EdgeVoyager.csproj
  3. 56 28
      Form1.cs
  4. 2 0
      Program.cs
  5. 38 0
      Settings1.Designer.cs
  6. 9 0
      Settings1.settings

+ 15 - 0
App.config

@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<configuration>
+    <configSections>
+        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
+            <section name="EdgeVoyager.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
+        </sectionGroup>
+    </configSections>
+    <userSettings>
+        <EdgeVoyager.Settings1>
+            <setting name="firstwindow" serializeAs="String">
+                <value>True</value>
+            </setting>
+        </EdgeVoyager.Settings1>
+    </userSettings>
+</configuration>

+ 12 - 0
EdgeVoyager.csproj

@@ -18,6 +18,11 @@
       <AutoGen>True</AutoGen>
       <DependentUpon>Resources.resx</DependentUpon>
     </Compile>
+    <Compile Update="Settings1.Designer.cs">
+      <DesignTimeSharedInput>True</DesignTimeSharedInput>
+      <AutoGen>True</AutoGen>
+      <DependentUpon>Settings1.settings</DependentUpon>
+    </Compile>
   </ItemGroup>
 
   <ItemGroup>
@@ -27,4 +32,11 @@
     </EmbeddedResource>
   </ItemGroup>
 
+  <ItemGroup>
+    <None Update="Settings1.settings">
+      <Generator>SettingsSingleFileGenerator</Generator>
+      <LastGenOutput>Settings1.Designer.cs</LastGenOutput>
+    </None>
+  </ItemGroup>
+
 </Project>

+ 56 - 28
Form1.cs

@@ -1,4 +1,12 @@
 using Microsoft.Web.WebView2.Core;
+using System.Drawing.Imaging;
+using System;
+using System.Drawing;
+using System.IO;
+using System.Net.Http;
+using System.Windows.Forms;
+using Microsoft.Web.WebView2.Core;
+using Microsoft.Web.WebView2.WinForms;
 
 namespace EdgeVoyager
 {
@@ -8,13 +16,30 @@ namespace EdgeVoyager
         public Form1()
         {
             InitializeComponent();
-            InitializeAsync();
+            InitializeAsync(); 
+        }
+
+        private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
+        {
+            Form1 newForm = new Form1();
+            // 设置新窗口中WebView2的Source属性为要打开的链接
+            newForm.webView21.Source = new Uri(e.Uri);
+            // 显示新窗口
+            newForm.Show();
+            // 设置Handled为true,表示已经处理了新窗口请求
+            e.Handled = true;
         }
 
         async void InitializeAsync()
         {
             await webView21.EnsureCoreWebView2Async(null);
-            webView21.CoreWebView2.Navigate("https://cn.bing.com/?mkt=zh-CN");
+            webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
+            if (Settings1.Default.firstwindow == true)
+            {
+                webView21.CoreWebView2.Navigate("https://cn.bing.com/?mkt=zh-CN");
+                Settings1.Default.firstwindow = false;
+                Settings1.Default.Save();
+            }
         }
 
         private void back_button_Click(object sender, EventArgs e)
@@ -44,7 +69,6 @@ namespace EdgeVoyager
 
         private void webView21_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
         {
-            int num = 0;
             string currentUrl = webView21.Source.ToString();
             if (!comboBox1.Items.Contains(currentUrl))
             {
@@ -54,31 +78,6 @@ namespace EdgeVoyager
             progressBar.Value = 0;
             progressLabel.Text = "0%";
             StatusLabel.Text = "开始导航到:" + currentUrl; 
-            if (num != 0)
-            {
-                Form1 newForm = new Form1();
-
-                // 等待新窗口的WebView2控件初始化完成
-                newForm.webView21.CoreWebView2InitializationCompleted += (s, args) =>
-                {
-                    if (args.IsSuccess)
-                    {
-                        // 设置新窗口中WebView2控件的导航目标为当前要打开的URL
-                        newForm.webView21.CoreWebView2.Navigate(e.Uri);
-                    }
-                    else
-                    {
-                        // 初始化失败,可以进行相应的错误处理
-                        MessageBox.Show("WebView2初始化失败:" + args.InitializationException.Message);
-                    }
-                };
-
-                // 显示新窗口
-                newForm.Show();
-
-                // 取消当前的导航请求
-                e.Cancel = true;
-            }
         }
 
         private async void webView21_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
@@ -94,6 +93,35 @@ namespace EdgeVoyager
             StatusLabel.Text = "完成。"; 
             string title = await webView21.CoreWebView2.ExecuteScriptAsync("document.title;");
             this.Text = "LYKNS EdgeVoyager:" + title.Trim('"');
+
+            string faviconUrl = await webView21.CoreWebView2.ExecuteScriptAsync("Array.from(document.querySelectorAll('link[rel=\"icon\"], link[rel=\"shortcut icon\"]')).map(link => link.href).find(url => url);");
+            faviconUrl = faviconUrl.Trim('"'); // 去掉引号
+
+            if (!string.IsNullOrEmpty(faviconUrl))
+            {
+                using (var client = new HttpClient())
+                {
+                    var faviconData = await client.GetByteArrayAsync(faviconUrl);
+                    using (var ms = new MemoryStream(faviconData))
+                    {
+                        using (var img = Image.FromStream(ms))
+                        {
+                            if (img is Bitmap bitmap)
+                            {
+                                this.Icon = Icon.FromHandle(bitmap.GetHicon());
+                            }
+                            else
+                            {
+                                // 如果图片不是Bitmap类型,可以考虑其他方式来获取图标
+                                // 例如,你可以尝试将图片保存到文件,然后使用Icon.ExtractAssociatedIcon方法获取图标
+                                // 或者直接使用img作为窗体的图标(如果可行)
+                                // 这里以直接使用img作为窗体图标为例(需确保img可以作为窗体图标)
+                                this.Icon = Icon.FromHandle(((Bitmap)img.Clone()).GetHicon());
+                            }
+                        }
+                    }
+                }
+            }
         }
 
         private void comboBox1_KeyDown(object sender, KeyEventArgs e)

+ 2 - 0
Program.cs

@@ -11,6 +11,8 @@ namespace EdgeVoyager
             // To customize application configuration such as set high DPI settings or default font,
             // see https://aka.ms/applicationconfiguration.
             ApplicationConfiguration.Initialize();
+            Settings1.Default.firstwindow = true;
+            Settings1.Default.Save();
             Application.Run(new Form1());
         }
     }

+ 38 - 0
Settings1.Designer.cs

@@ -0,0 +1,38 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+//     此代码由工具生成。
+//     运行时版本:4.0.30319.42000
+//
+//     对此文件的更改可能会导致不正确的行为,并且如果
+//     重新生成代码,这些更改将会丢失。
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace EdgeVoyager {
+    
+    
+    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.12.0.0")]
+    internal sealed partial class Settings1 : global::System.Configuration.ApplicationSettingsBase {
+        
+        private static Settings1 defaultInstance = ((Settings1)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings1())));
+        
+        public static Settings1 Default {
+            get {
+                return defaultInstance;
+            }
+        }
+        
+        [global::System.Configuration.UserScopedSettingAttribute()]
+        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+        [global::System.Configuration.DefaultSettingValueAttribute("True")]
+        public bool firstwindow {
+            get {
+                return ((bool)(this["firstwindow"]));
+            }
+            set {
+                this["firstwindow"] = value;
+            }
+        }
+    }
+}

+ 9 - 0
Settings1.settings

@@ -0,0 +1,9 @@
+<?xml version='1.0' encoding='utf-8'?>
+<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="EdgeVoyager" GeneratedClassName="Settings1">
+  <Profiles />
+  <Settings>
+    <Setting Name="firstwindow" Type="System.Boolean" Scope="User">
+      <Value Profile="(Default)">True</Value>
+    </Setting>
+  </Settings>
+</SettingsFile>