using System.Collections;
using System.Diagnostics;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
namespace EdgeVoyager
{
public partial class Form1 : Form
{
int zoom = 100;
private bool isWebView2Focused = false;
private HttpClient httpClient = new HttpClient();
public Form1()
{
InitializeComponent();
InitializeAsync();
}
private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
{
Form1 newForm = new Form1();
newForm.webView21.Source = new Uri(e.Uri);
newForm.Show();
e.Handled = true;
}
async void InitializeAsync()
{
await webView21.EnsureCoreWebView2Async(null);
string resxFilePath = "favoritesMenuItem.resx";
using (ResXResourceReader reader = new ResXResourceReader(resxFilePath))
{
foreach (DictionaryEntry entry in reader)
{
string resourceName = entry.Key.ToString();
string resourceValue = entry.Value.ToString();
ToolStripMenuItem menuItem = new ToolStripMenuItem
{
Text = resourceName,
Tag = resourceValue
};
menuItem.Click += MenuItem_Click;
收藏夹AToolStripMenuItem.DropDownItems.Add(menuItem);
}
}
webView21.CoreWebView2.WebResourceRequested += WebView2_WebResourceRequested;
await webView21.CoreWebView2.ExecuteScriptAsync("window.onload=function(){window.chrome.webview.postMessage('100');};");
webView21.CoreWebView2.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Light;
webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
webView21.GotFocus += (s, e) => isWebView2Focused = true;
webView21.LostFocus += (s, e) => isWebView2Focused = false;
if (Settings1.Default.firstwindow == true)
{
string htmlString = @"
起始页
";
webView21.CoreWebView2.NavigateToString(htmlString);
Settings1.Default.firstwindow = false;
Settings1.Default.Save();
}
}
private void back_button_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.GoBack();
}
private void forward_button_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.GoForward();
}
private void refresh_button_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.Reload();
}
private void stop_button_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.Stop();
}
private void search_button_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
if (comboBox1.Text != "about:blank")
{
Form1 newForm = new Form1();
newForm.webView21.Source = new Uri("https://cn.bing.com/search?q=" + textBox1.Text);
newForm.Show();
}
else
{
webView21.CoreWebView2.Navigate("https://cn.bing.com/search?q=" + textBox1.Text);
webView21.CoreWebView2.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Light;
}
}
}
private bool isHttpsFallback = false;
private void webView21_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
{
string uri = e.Uri;
if (uri.StartsWith("http://"))
{
string httpsUri = "https://" + uri.Substring("http://".Length);
e.Cancel = true; // 取消当前的http导航
webView21.CoreWebView2.Navigate(httpsUri); // 尝试https导航
}
string currentUrl = webView21.Source.ToString();
if (!comboBox1.Items.Contains(currentUrl))
{
comboBox1.Items.Add(currentUrl);
}
comboBox1.Text = currentUrl;
progressBar.Value = 0;
progressLabel.Text = "0%";
StatusLabel.Text = "开始导航到:" + currentUrl;
}
private async void webView21_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (!e.IsSuccess && isHttpsFallback)
{
isHttpsFallback = false; // 重置标志
string originalUri = webView21.CoreWebView2.Source.Replace("https://", "http://");
webView21.CoreWebView2.Navigate(originalUri); // 重新导航到http地址
}
else if (e.IsSuccess && webView21.CoreWebView2.Source.StartsWith("https://"))
{
isHttpsFallback = false; // 如果https导航成功,重置标志
}
string currentUrl = webView21.Source.ToString();
if (!comboBox1.Items.Contains(currentUrl))
{
comboBox1.Items.Add(currentUrl);
}
comboBox1.Text = currentUrl;
progressBar.Value = 100;
progressLabel.Text = "100%";
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))
{
Uri uriResult;
bool isAbsoluteUri = Uri.TryCreate(faviconUrl, UriKind.Absolute, out uriResult);
if (isAbsoluteUri)
{
using (var client = new HttpClient())
{
var faviconData = await client.GetByteArrayAsync(uriResult);
using (var ms = new MemoryStream(faviconData))
{
using (var img = Image.FromStream(ms))
{
if (img is Bitmap bitmap)
{
this.Icon = Icon.FromHandle(bitmap.GetHicon());
}
else
{
this.Icon = Icon.FromHandle(((Bitmap)img.Clone()).GetHicon());
}
}
}
}
}
}
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string input = comboBox1.Text;
if (!input.StartsWith("http://") && !input.StartsWith("https://"))
{
comboBox1.Text = "https://" + input;
comboBox1.SelectionStart = comboBox1.Text.Length;
}
string url = comboBox1.Text;
if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
{
webView21.CoreWebView2.Navigate(url);
}
}
}
private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void webView21_ContentLoading(object sender, CoreWebView2ContentLoadingEventArgs e)
{
progressBar.Value = 50;
progressLabel.Text = "50%";
StatusLabel.Text = "内容开始加载";
}
private async void SetZoomLevel(double zoomLevel)
{
await webView21.CoreWebView2.ExecuteScriptAsync($"document.body.style.zoom = '{zoomLevel}%'");
}
private void toolStripSplitButton1_ButtonClick(object sender, EventArgs e)
{
SetZoomLevel(100);
toolStripMenuItem3.Enabled = true;
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
zoom = zoom + 25;
SetZoomLevel(zoom);
toolStripMenuItem3.Enabled = true;
}
private void toolStripMenuItem3_Click(object sender, EventArgs e)
{
zoom = zoom - 25;
SetZoomLevel(zoom);
if (zoom == 25)
toolStripMenuItem3.Enabled = false;
}
private void 刷新RToolStripMenuItem_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.Reload();
}
private void 停止TToolStripMenuItem_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.Stop();
}
private void 前进QToolStripMenuItem_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.GoForward();
}
private void 后退WToolStripMenuItem_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.GoBack();
}
private void webView21_SourceChanged(object sender, CoreWebView2SourceChangedEventArgs e)
{
StatusLabel.Text = "源地址已更改";
}
private void WebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
{
string requestUri = e.Request.Uri;
StatusLabel.Text = "请求资源:" + requestUri;
}
private void 工具栏ToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
if (工具栏ToolStripMenuItem.Checked == true)
{
statusStrip1.Visible = true;
webView21.Height = webView21.Height - 23;
}
else
{
statusStrip1.Visible = false;
webView21.Height = webView21.Height + 23;
}
}
private void 关于EdgeVoyagerToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 aboutBox1 = new AboutBox1();
aboutBox1.ShowDialog();
}
private void 新建NToolStripMenuItem_Click(object sender, EventArgs e)
{
Settings1.Default.firstwindow = true;
Settings1.Default.Save();
Form1 newForm = new Form1();
newForm.Show();
}
private void 打开OToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "网页文件 (*.html;*.htm)|*.html;*.htm|可缩放矢量图形文件 (*.svg)|*.svg|所有文件 (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
Form1 newForm = new Form1();
newForm.webView21.Source = new Uri("file:///" + filePath);
newForm.Show();
}
}
private async void 保存SToolStripMenuItem_ClickAsync(object sender, EventArgs e)
{
}
private async void 打印PToolStripMenuItem_Click(object sender, EventArgs e)
{
string title = webView21.CoreWebView2.DocumentTitle;
try
{
CoreWebView2PrintStatus printStatus = await webView21.CoreWebView2.PrintAsync(null);
if (printStatus == CoreWebView2PrintStatus.Succeeded)
{
MessageBox.Show(this, "打印 " + title + " 文档到打印机成功", "打印到默认打印机");
}
else if (printStatus == CoreWebView2PrintStatus.PrinterUnavailable)
{
MessageBox.Show(this, "打印机不可用,离线或错误状态", "打印到默认打印机");
}
else
{
MessageBox.Show(this, "打印 " + title + " 文档到打印机失败", "打印到默认打印机");
}
}
catch (Exception)
{
MessageBox.Show(this, "打印 " + title + " 文档已在进行中", "打印到默认打印机");
}
}
private void 打印预览VToolStripMenuItem_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.ShowPrintUI();
}
private void 发送SToolStripMenuItem_Click(object sender, EventArgs e)
{
string mailtoLink = $"mailto:?subject=共享网页&body=请查看这个网页:" + comboBox1.Text;
Process.Start(new ProcessStartInfo
{
FileName = mailtoLink,
UseShellExecute = true
});
}
private async void 属性PToolStripMenuItem_Click(object sender, EventArgs e)
{
string title = webView21.CoreWebView2.DocumentTitle;
string url = webView21.CoreWebView2.Source;
string content = await GetWebPageContent(url);
int charCount = content.Length;
int byteCount = Encoding.UTF8.GetByteCount(content);
string encoding = "UTF-8";
string language = "zh-CN";
string contentType = "text/html";
string author = await GetMetaData("author");
string description = await GetMetaData("description");
string keywords = await GetMetaData("keywords");
string updateDate = await GetMetaData("last-modified");
string securityInfo = await GetSecurityInfo(url);
string securityLevel = "High";
string faviconUrl = await GetFaviconUrl();
string encodingLanguage = "HTML, JavaScript";
MessageBox.Show(
$"常规信息:\n" +
$"标题:{title}\n" +
$"地址(URL):{url}\n" +
$"编码:{encoding}\n" +
$"语言:{language}\n" +
$"内容类型:{contentType}\n" +
$"\n网页内容信息:\n" +
$"字符数:{charCount}\n" +
$"字节数:{byteCount}\n" +
$"编码方式:HTML, XML\n" +
$"\n网页元数据:\n" +
$"作者:{author}\n" +
$"描述:{description}\n" +
$"关键词:{keywords}\n" +
$"更新日期:{updateDate}\n" +
$"\n网页安全信息:\n" +
$"安全证书信息:{securityInfo}\n" +
$"安全级别:{securityLevel}\n" +
$"\n其他信息:\n" +
$"收藏夹图标:{faviconUrl}\n" +
$"编码语言:{encodingLanguage}",
"网页属性",
MessageBoxButtons.OK,
MessageBoxIcon.Information
);
}
private async Task GetWebPageContent(string url)
{
try
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
return ex.Message;
}
}
private async Task GetMetaData(string name)
{
try
{
string script = $"document.querySelector('meta[name=\"{name}\"]').content;";
return await webView21.CoreWebView2.ExecuteScriptAsync(script);
}
catch (Exception)
{
return "不可用";
}
}
private async Task GetFaviconUrl()
{
try
{
string script = "Array.from(document.querySelectorAll('link[rel=\"icon\"], link[rel=\"shortcut icon\"]')).map(link => link.href).find(url => url);";
string faviconUrl = await webView21.CoreWebView2.ExecuteScriptAsync(script);
return faviconUrl.Trim('"');
}
catch (Exception)
{
return "不可用";
}
}
private async Task GetSecurityInfo(string url)
{
try
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
if (response.RequestMessage.RequestUri.Scheme == "https")
{
var headers = response.Headers;
if (headers.Contains("Strict-Transport-Security"))
{
return "HSTS已开启";
}
}
return "无HSTS";
}
catch (Exception ex)
{
return ex.Message;
}
}
private void 剪切TToolStripMenuItem_Click(object sender, EventArgs e)
{
if (comboBox1.Focused)
{
if (comboBox1.SelectedText != "")
{
Clipboard.SetText(comboBox1.SelectedText);
comboBox1.Text = comboBox1.Text.Remove(comboBox1.SelectionStart, comboBox1.SelectionLength);
comboBox1.Focus();
}
}
else if (textBox1.Focused)
{
if (textBox1.SelectedText != "")
{
Clipboard.SetText(textBox1.SelectedText);
textBox1.Text = textBox1.Text.Remove(textBox1.SelectionStart, textBox1.SelectionLength);
}
}
}
private async void 复制CToolStripMenuItem_Click(object sender, EventArgs e)
{
if (comboBox1.Focused)
{
if (comboBox1.SelectedText != "")
{
Clipboard.SetText(comboBox1.SelectedText);
}
}
else if (textBox1.Focused)
{
if (textBox1.SelectedText != "")
{
Clipboard.SetText(textBox1.SelectedText);
}
}
else if (isWebView2Focused)
{
string script = "window.getSelection().toString();";
string selectedText = await webView21.CoreWebView2.ExecuteScriptAsync(script);
selectedText = selectedText.Trim('"');
if (!string.IsNullOrEmpty(selectedText))
{
Clipboard.SetText(selectedText);
}
}
}
private async void 粘贴PToolStripMenuItem_Click(object sender, EventArgs e)
{
if (comboBox1.Focused)
{
if (comboBox1.SelectionLength > 0)
{
string clipboardText = Clipboard.GetText();
comboBox1.Text = comboBox1.Text.Remove(comboBox1.SelectionStart, comboBox1.SelectionLength) + clipboardText;
comboBox1.SelectionStart = comboBox1.Text.Length;
}
else
{
string clipboardText = Clipboard.GetText();
comboBox1.Text += clipboardText;
comboBox1.SelectionStart = comboBox1.Text.Length;
}
}
else if (textBox1.Focused)
{
textBox1.Paste();
}
}
private async void 全选AToolStripMenuItem_Click(object sender, EventArgs e)
{
if (comboBox1.Focused)
{
comboBox1.SelectAll();
}
else if (textBox1.Focused)
{
textBox1.SelectAll();
}
else
{
string script = "document.execCommand('selectAll', false, null);";
await webView21.CoreWebView2.ExecuteScriptAsync(script);
}
}
private void 查找FToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private async void 添加到收藏夹ToolStripMenuItem_Click(object sender, EventArgs e)
{
string resxFilePath = "favoritesMenuItem.resx";
string title = await webView21.CoreWebView2.ExecuteScriptAsync("document.title;");
string pageTitle = title.Trim('"');
string pageUrl = webView21.CoreWebView2.Source.ToString();
bool titleExists = false;
using (ResXResourceReader reader = new ResXResourceReader(resxFilePath))
{
foreach (DictionaryEntry entry in reader)
{
if (entry.Key.ToString() == pageTitle)
{
titleExists = true;
break;
}
}
}
if (!titleExists)
{
ResXResourceReader reader = new ResXResourceReader(resxFilePath);
Hashtable resources = new Hashtable();
foreach (DictionaryEntry entry in reader)
{
resources.Add(entry.Key, entry.Value);
}
reader.Close();
// 添加新的资源项
resources.Add(pageTitle, pageUrl);
// 写入到资源文件
using (ResXResourceWriter writer = new ResXResourceWriter(resxFilePath))
{
foreach (DictionaryEntry entry in resources)
{
writer.AddResource(entry.Key.ToString(), entry.Value);
}
writer.Generate();
}
for (int i = 0; i < 收藏夹AToolStripMenuItem.DropDownItems.Count; i++)
{
// 如果找到了toolStripSeparator10
if (收藏夹AToolStripMenuItem.DropDownItems[i] is ToolStripSeparator &&
收藏夹AToolStripMenuItem.DropDownItems[i].Name == "toolStripSeparator10")
{
// 从toolStripSeparator10下方开始,删除所有按钮
for (int j = 收藏夹AToolStripMenuItem.DropDownItems.Count - 1; j > i; j--)
{
收藏夹AToolStripMenuItem.DropDownItems.RemoveAt(j);
}
break; // 找到并处理完毕后退出循环
}
}
using (ResXResourceReader reader1 = new ResXResourceReader(resxFilePath))
{
foreach (DictionaryEntry entry in reader1)
{
string resourceName = entry.Key.ToString();
string resourceValue = entry.Value.ToString();
ToolStripMenuItem menuItem = new ToolStripMenuItem
{
Text = resourceName,
Tag = resourceValue
};
menuItem.Click += MenuItem_Click;
收藏夹AToolStripMenuItem.DropDownItems.Add(menuItem);
}
}
}
}
private async Task DownloadFaviconAsync(string faviconUrl)
{
using (HttpClient client = new HttpClient())
{
try
{
return await client.GetByteArrayAsync(faviconUrl);
}
catch (Exception ex)
{
return null;
}
}
}
private void MenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem)sender;
string url = (string)menuItem.Tag;
webView21.CoreWebView2.Navigate(url);
}
private void 整理收藏夹ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
string resxFilePath = "favoritesMenuItem.resx";
for (int i = 0; i < 收藏夹AToolStripMenuItem.DropDownItems.Count; i++)
{
// 如果找到了toolStripSeparator10
if (收藏夹AToolStripMenuItem.DropDownItems[i] is ToolStripSeparator &&
收藏夹AToolStripMenuItem.DropDownItems[i].Name == "toolStripSeparator10")
{
// 从toolStripSeparator10下方开始,删除所有按钮
for (int j = 收藏夹AToolStripMenuItem.DropDownItems.Count - 1; j > i; j--)
{
收藏夹AToolStripMenuItem.DropDownItems.RemoveAt(j);
}
break; // 找到并处理完毕后退出循环
}
}
using (ResXResourceReader reader1 = new ResXResourceReader(resxFilePath))
{
foreach (DictionaryEntry entry in reader1)
{
string resourceName = entry.Key.ToString();
string resourceValue = entry.Value.ToString();
ToolStripMenuItem menuItem = new ToolStripMenuItem
{
Text = resourceName,
Tag = resourceValue
};
menuItem.Click += MenuItem_Click;
收藏夹AToolStripMenuItem.DropDownItems.Add(menuItem);
}
}
}
private void Form1_Activated(object sender, EventArgs e)
{
string resxFilePath = "favoritesMenuItem.resx";
for (int i = 0; i < 收藏夹AToolStripMenuItem.DropDownItems.Count; i++)
{
// 如果找到了toolStripSeparator10
if (收藏夹AToolStripMenuItem.DropDownItems[i] is ToolStripSeparator &&
收藏夹AToolStripMenuItem.DropDownItems[i].Name == "toolStripSeparator10")
{
// 从toolStripSeparator10下方开始,删除所有按钮
for (int j = 收藏夹AToolStripMenuItem.DropDownItems.Count - 1; j > i; j--)
{
收藏夹AToolStripMenuItem.DropDownItems.RemoveAt(j);
}
break; // 找到并处理完毕后退出循环
}
}
using (ResXResourceReader reader1 = new ResXResourceReader(resxFilePath))
{
foreach (DictionaryEntry entry in reader1)
{
string resourceName = entry.Key.ToString();
string resourceValue = entry.Value.ToString();
ToolStripMenuItem menuItem = new ToolStripMenuItem
{
Text = resourceName,
Tag = resourceValue
};
menuItem.Click += MenuItem_Click;
收藏夹AToolStripMenuItem.DropDownItems.Add(menuItem);
}
}
}
}
}