-
Notifications
You must be signed in to change notification settings - Fork 2
/
MainForm.cs
217 lines (186 loc) · 7.2 KB
/
MainForm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright (c) Thomas Gossler. All rights reserved.
// Licensed under the MIT license.
#nullable disable warnings
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace WebPageHost;
public partial class MainForm : Form
{
// Custom form events
public EventHandler FormLoaded;
// WebView2
public WebView2 WebView { get; private set; }
private bool isWebViewInitialized;
private readonly string userDataFolderName;
public EventHandler WebViewDOMContentLoaded;
// Properties
public string Url {
get => url;
set {
url = value;
if (isWebViewInitialized) {
NavigateToUrl(Url);
}
}
}
private string url;
public string Title { get; set; }
private string buttonTitle;
public string ButtonTitle {
get => buttonTitle;
set {
buttonTitle = value;
bool showButton = !string.IsNullOrWhiteSpace(buttonTitle);
button.Visible = showButton;
if (showButton) {
button.Text = buttonTitle;
button.AutoSize = buttonTitle.Length > 20;
UpdateButtonPlacement();
}
}
}
private void UpdateButtonPlacement()
{
if (!string.IsNullOrWhiteSpace(buttonTitle)) {
button.Left = (Width - button.Width) / 2;
button.Top = ClientSize.Height - button.Height - (button.Height / 3);
if (WebView != null) {
WebView.Height = ClientSize.Height - button.Height - (button.Height * 2 / 3);
}
}
else {
if (WebView != null) {
WebView.Height = ClientSize.Height;
}
}
}
private readonly bool isTitleGiven;
public bool DisableSso { get; set; }
public bool SuppressCertErrors { get; set; }
// MainForm
public MainForm(string userDataFolderName, string url, string title = "", bool disableSso = false, bool suppressCertErrors = false)
{
if (string.IsNullOrWhiteSpace(userDataFolderName)) {
throw new ArgumentException("Parameter 'userDataFolderName' is required");
}
if (string.IsNullOrWhiteSpace(url)) {
throw new ArgumentException("Parameter 'url' is required");
}
Url = url;
Title = title;
isTitleGiven = !string.IsNullOrWhiteSpace(title);
DisableSso = disableSso;
SuppressCertErrors = suppressCertErrors;
this.userDataFolderName = userDataFolderName;
AutoScaleMode = AutoScaleMode.Dpi;
InitializeComponent();
}
private async void MainForm_Load(object sender, EventArgs e)
{
// Initialize WebView2
CoreWebView2Environment webViewEnv = await CoreWebView2Environment.CreateAsync(null, userDataFolderName,
new CoreWebView2EnvironmentOptions() { AllowSingleSignOnUsingOSPrimaryAccount = !DisableSso });
WebView = new WebView2();
SuspendLayout();
Controls.Add(WebView);
((System.ComponentModel.ISupportInitialize)WebView).BeginInit();
WebView.Parent = this;
WebView.Name = "webView";
WebView.CreationProperties = null;
int padding = 0;
WebView.Bounds = new Rectangle(padding, padding, ClientSize.Width - (2 * padding), ClientSize.Height - (2 * padding));
WebView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
WebView.DefaultBackgroundColor = System.Drawing.Color.White;
WebView.ZoomFactor = 1D;
WebView.Visible = true;
((System.ComponentModel.ISupportInitialize)WebView).EndInit();
ResumeLayout(true);
WebView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
await WebView.EnsureCoreWebView2Async(webViewEnv);
WebView.NavigationCompleted += WebView_NavigationCompleted;
// Initialize web content
isWebViewInitialized = true;
NavigateToUrl(Url);
UpdateFormTitle(Title, Url);
UpdateButtonPlacement();
// Raise form loaded event
FormLoaded?.Invoke(this, new EventArgs());
}
private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
if (SuppressCertErrors) {
WebView.CoreWebView2.CallDevToolsProtocolMethodAsync("Security.setIgnoreCertificateErrors", "{\"ignore\": true}");
}
WebView.CoreWebView2.NewWindowRequested += (s, e) => e.NewWindow = WebView.CoreWebView2;
WebView.CoreWebView2.SourceChanged += (s, e) => url = WebView.Source.AbsoluteUri; // update field directly not using setter to avoid navigation
WebView.CoreWebView2.DocumentTitleChanged += (s, e) => {
if (!isTitleGiven) {
Text = WebView.CoreWebView2.DocumentTitle;
}
};
WebView.CoreWebView2.DOMContentLoaded += async (s, e) => {
WebViewDOMContentLoaded?.Invoke(s, e);
var coreWebView = (CoreWebView2)s;
string favIconUrl = string.Empty;
if (coreWebView != null) {
favIconUrl = await coreWebView.ExecuteScriptAsync("document.querySelector(\"link[rel~= 'icon']\").href");
}
if (!string.IsNullOrEmpty(favIconUrl)) {
_ = UpdateFormIcon(favIconUrl);
}
};
}
private void WebView_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
// Workaround for bug in earlier WebView2 version where webViewControl.Focus() was not working correctly
IntPtr child = Win32Interop.GetWindow(WebView.Handle, Win32Interop.GW_CHILD);
_ = Win32Interop.SetFocus(child);
}
private void UpdateFormTitle(string text, string url)
{
string title = isTitleGiven ? text : url.ToLower();
Text = title;
}
private async Task UpdateFormIcon(string favIconUrl)
{
string iconUrl = favIconUrl.Replace("\"", "");
try {
using var httpClient = new HttpClient();
byte[] imageBytes = await httpClient.GetByteArrayAsync(iconUrl);
if (null != imageBytes && imageBytes.Length > 0) {
try {
await using var ms = new MemoryStream(imageBytes);
Icon = new Icon(ms);
}
catch (Exception) {
await using var ms = new MemoryStream(imageBytes);
var bitmap = new Bitmap(ms);
IntPtr iconHandle = bitmap.GetHicon();
Icon = Icon.FromHandle(iconHandle);
}
}
}
catch (Exception) {
Trace.TraceWarning("Favicon could not be retrieved");
}
}
private void NavigateToUrl(string url)
{
WebView.CoreWebView2.Navigate(url);
}
private void button_Click(object sender, EventArgs e)
{
Close();
}
private void MainForm_Resize(object sender, EventArgs e)
{
UpdateButtonPlacement();
}
}