-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainForm.cs
311 lines (265 loc) · 11.1 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// 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.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.ComponentModel;
namespace WebPageHost;
public partial class MainForm : Form
{
// Custom form events
public EventHandler FormLoaded;
// WebView2
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public WebView2 WebView { get; private set; }
private Label cover;
private bool isWebViewInitialized;
private bool isWebPageColorModeInitialized = true;
private static string UserDataFolderName;
public EventHandler WebViewDOMContentLoaded;
// Properties
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Url {
get => url;
set {
url = value;
if (isWebViewInitialized) {
NavigateToUrl(Url);
}
}
}
private string url;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Title { get; set; }
private string buttonTitle;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
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();
}
}
}
public static string UserDataFolderPath
{
get {
var appDataBasePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var baseFolderPath = Path.Combine(appDataBasePath, Common.ProgramName);
var userDataFolderPath = Path.Combine(baseFolderPath, UserDataFolderName);
return userDataFolderPath;
}
}
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;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool DisableSso { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool SuppressCertErrors { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool ForceDarkMode { get; set; }
// MainForm
public MainForm(string userDataFolderName, string url, string title = "", bool disableSso = false, bool suppressCertErrors = false, bool forceDarkMode = 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;
ForceDarkMode = forceDarkMode;
SuppressCertErrors = suppressCertErrors;
UserDataFolderName = userDataFolderName;
AutoScaleMode = AutoScaleMode.Dpi;
InitializeComponent();
}
private async void MainForm_Load(object sender, EventArgs e)
{
// Initialize WebView2
var forceDarkMode = Application.IsDarkModeEnabled && ForceDarkMode;
var options = new CoreWebView2EnvironmentOptions(forceDarkMode ? "--enable-features=WebContentsForceDark" : "") {
AllowSingleSignOnUsingOSPrimaryAccount = !DisableSso
};
CoreWebView2Environment webViewEnv = await CoreWebView2Environment.CreateAsync(null, UserDataFolderPath, options);
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 = Application.IsDarkModeEnabled ? System.Drawing.Color.DarkGray : 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;
// Display a loading label with centered text indicating progress
cover = new Label {
Dock = DockStyle.Fill,
BackColor = Application.IsDarkModeEnabled ? SystemColors.Control : WebView.DefaultBackgroundColor,
Text = "...",
Font = new Font("Segoe UI", 48, FontStyle.Bold),
TextAlign = ContentAlignment.MiddleCenter,
};
Controls.Add(cover);
cover.BringToFront();
// 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}");
}
if (Application.IsDarkModeEnabled) {
WebView.CoreWebView2.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Dark;
isWebPageColorModeInitialized = false;
}
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 GetFavIconUrlWithRetry(coreWebView);
}
if (!string.IsNullOrEmpty(favIconUrl)) {
_ = UpdateFormIcon(favIconUrl);
}
};
}
private void WebView_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (!isWebPageColorModeInitialized) {
isWebPageColorModeInitialized = true;
// Workaround for bug in WebView2 where setting PreferredColorScheme to Dark does not work on first load
WebView.CoreWebView2.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Dark;
WebView.CoreWebView2.Reload();
return;
}
cover.Visible = false;
cover.Dispose();
cover = null;
// 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 async Task<string> GetFavIconUrlWithRetry(CoreWebView2 coreWebView, int maxRetries = 3, int delayMilliseconds = 1000)
{
string favIconUrl = string.Empty;
for (int attempt = 0; attempt < maxRetries; attempt++) {
try {
favIconUrl = await coreWebView.ExecuteScriptAsync("document.querySelector(\"link[rel~= 'icon']\").href");
favIconUrl = favIconUrl.Replace("null", "");
if (!string.IsNullOrEmpty(favIconUrl)) {
return favIconUrl;
}
favIconUrl = coreWebView.FaviconUri;
if (!string.IsNullOrEmpty(favIconUrl)) {
return favIconUrl;
}
}
catch (Exception) {
// Log the exception if needed
}
await Task.Delay(delayMilliseconds);
}
return favIconUrl;
}
private void UpdateFormTitle(string text, string url)
{
string title = isTitleGiven ? text : url.ToLower();
Text = title;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
private const int WM_SETICON = 0x80;
private const int ICON_SMALL = 0;
private const int ICON_BIG = 1;
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);
}
// Explicitly update taskbar icons after changing the form icon.
SendMessage(this.Handle, WM_SETICON, new IntPtr(ICON_SMALL), Icon.Handle);
SendMessage(this.Handle, WM_SETICON, new IntPtr(ICON_BIG), Icon.Handle);
}
}
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();
}
}