-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm1.cs
612 lines (530 loc) · 21.3 KB
/
Form1.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace ForumBrowser
{
public partial class Form1 : Form
{
private readonly Settings settings;
private Dictionary<WebView2, List<(string title, string url)>> histories = new();
public Form1()
{
InitializeComponent();
settings = new(this);
// Initialize the WebView2 environment when the form is created
_ = InitializeWebView2Environment();
}
private async Task InitializeWebView2Environment()
{
string browserOptions = "--disable-features=msWebOOUI,msPdfOOUI,msSmartScreenProtection,ElasticOverscroll";
browserOptions += " --disable-background-networking ";
if (settings.AllowCORS)
{
browserOptions += " --disable-web-security";
}
if (settings.UnlimitedStorage)
{
browserOptions += " --disable-features=ElasticOverscroll";
}
string cacheDir = Environment.CurrentDirectory + @"\Cache\";
await WebView2Manager.InitializeEnvironmentAsync(browserOptions, cacheDir);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
// Clean up WebView2 resources when the form is closing
WebView2Manager.Cleanup();
}
private void Form1_Load(object sender, EventArgs e)
{
toolStripStatusLabel1.Text = "";
toolStrip1.Renderer = new ToolStripProfessionalRenderer()
{
RoundedEdges = false
};
void resizeCallback(object? s, EventArgs e)
{
int _padding = 5;
tabControl.Left = _padding;
tabControl.Width = Width - (20 + _padding);
tabControl.Height = Height - 95;
int countOfToolStripItems = toolStrip1.Items.Count;
int toolStripItemWidth = toolStrip1.Items[0].Width;
//txtUrl.Left = countOfToolStripItems * 30;
txtUrl.Width = Width - (countOfToolStripItems * toolStripItemWidth + 35);
}
//form1 resize callback
this.Resize += resizeCallback;
resizeCallback(this, new EventArgs());
// when double click on tabcontrol empty space, add a new tab
// workaround: use form1 double click event and check if the mouse is on the tabcontrol
this.DoubleClick += (s, e) =>
{
if (tabControl.Bounds.Contains(((MouseEventArgs)e).Location))
{
NewTab("about:blank");
txtUrl.Text = "about:blank";
}
};
// on tab middle click, close the tab
tabControl.MouseClick += (s, e) =>
{
if (e.Button == MouseButtons.Middle)
{
for (int i = 0; i < tabControl.TabPages.Count; i++)
{
if (tabControl.GetTabRect(i).Contains(e.Location))
{
// Get the tab to close
TabPage tabToClose = tabControl.TabPages[i];
// Dispose WebView2 before removing the tab
DisposeWebView2InTab(tabToClose);
// Remove the tab
tabControl.TabPages.RemoveAt(i);
break;
}
}
}
// on right click, show context menu
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Show(tabControl, e.Location);
}
};
// Handle tab removal through TabControl.ControlRemoved
// Handle tab removal through TabControl.ControlRemoved
tabControl.ControlRemoved += (s, e) =>
{
if (e.Control is TabPage tabPage)
{
DisposeWebView2InTab(tabPage);
}
};
// on tab change event, change the txtUrl.Text
tabControl.SelectedIndexChanged += (s, e) =>
{
if (tabControl.SelectedTab != null && tabControl.SelectedTab.Controls.Count != 0)
{
WebView2 webview2 = (WebView2)tabControl.SelectedTab.Controls[0];
txtUrl.Text = webview2.Source.ToString();
SetFormTitle(webview2.CoreWebView2.DocumentTitle);
}
};
bool boolTxtFirstFocus = false;
txtUrl.LostFocus += (s, e) =>
{
boolTxtFirstFocus = true;
if (txtUrl.Text == "")
{
var currentTab = tabControl.SelectedTab;
if (currentTab != null && currentTab.Controls.Count != 0)
{
WebView2 webview2 = (WebView2)currentTab.Controls[0];
txtUrl.Text = webview2.Source.ToString();
}
}
};
txtUrl.Click += (s, e) =>
{
if (boolTxtFirstFocus)
{
txtUrl.SelectAll();
boolTxtFirstFocus = false;
}
};
//TxtUrl_KeyDown
txtUrl.KeyDown += (s, e) =>
{
//if ctrl+enter is pressed, add a new tab
if (e.Control && e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
EnteringUrl(true);
e.Handled = true;
}
//if enter is pressed, load the URL
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
// check if no tab is selected
bool isNewTab = tabControl.SelectedTab == null;
EnteringUrl(isNewTab);
e.Handled = true;
}
};
//tsback right click, show context menu
tsBack.MouseDown += (s, e) =>
{
if (e.Button == MouseButtons.Right)
{
//set contextMenuStripHistory items
contextMenuStripHistory.Items.Clear();
if (tabControl.SelectedTab != null && tabControl.SelectedTab.Controls.Count != 0)
{
WebView2 webview2 = (WebView2)tabControl.SelectedTab.Controls[0];
if (histories.ContainsKey(webview2))
{
foreach (var item in histories[webview2])
{
ToolStripMenuItem menuItem = new()
{
Text = item.title ?? item.url,
Tag = item
};
menuItem.Click += (s, e) =>
{
webview2.CoreWebView2.Navigate(item.url);
};
contextMenuStripHistory.Items.Add(menuItem);
}
}
}
contextMenuStripHistory.Show(this, e.Location);
}
};
txtUrl.Text = "https://www.google.com";
NavigateToUrl(txtUrl.Text);
}
private void TxtUrl_LostFocus(object? sender, EventArgs e)
{
throw new NotImplementedException();
}
/// <summary>
/// Properly disposes a WebView2 control contained in a TabPage
/// </summary>
private void DisposeWebView2InTab(TabPage tabPage)
{
if (tabPage != null && tabPage.Controls.Count > 0 && tabPage.Controls[0] is WebView2 webview2)
{
// Remove from histories dictionary
histories.Remove(webview2);
// Explicitly dispose the WebView2 control
try
{
// Cancel any pending navigation
if (webview2.CoreWebView2 != null)
{
try { webview2.CoreWebView2.NavigateToString("about:blank"); } catch { }
}
webview2.Source = new Uri("about:blank");
webview2.Dispose();
}
catch (Exception ex)
{
// Log exception if needed
System.Diagnostics.Debug.WriteLine($"Error disposing WebView2: {ex.Message}");
}
}
}
private void SetFormTitle(string title)
{
this.Text = title + " - ForumBrowser";
if (title == "")
{
this.Text = "ForumBrowser";
}
}
public async void NewTab(string url)
{
// this will add a new tab to tabControl and add a new WebView2 control to it
// after that, it will load URL to txtUrl.Text
TabPage tab = new()
{
Text = "New Tab"
};
tabControl.TabPages.Add(tab);
WebView2 webview2 = new()
{
Dock = DockStyle.Fill
};
// Use the shared WebView2 environment
await WebView2Manager.InitializeWebView2Async(webview2);
histories[webview2] = [];
//pass hotkey to form1
webview2.KeyDown += (s, e) =>
{
//log to toolstrip
toolStripStatusLabel1.Text = e.KeyCode.ToString();
toolStripStatusLabel1.Text += " " + e.Control.ToString();
if (e.KeyCode == Keys.T)
{
NewTab("about:blank");
txtUrl.Text = "about:blank";
}
if (e.KeyCode == Keys.W)
{
if (tabControl.SelectedTab != null)
{
// Get the tab to close
TabPage tabToClose = tabControl.SelectedTab;
// Dispose WebView2 before removing the tab
DisposeWebView2InTab(tabToClose);
// Remove the tab
tabControl.TabPages.Remove(tabToClose);
}
}
//ctrl+1, ctrl+2, ctrl+3, ctrl+4, ctrl+5, ctrl+6, ctrl+7, ctrl+8, ctrl+9
if (e.KeyCode >= Keys.D1 && e.KeyCode <= Keys.D9)
{
int index = e.KeyCode - Keys.D1;
if (index < tabControl.TabPages.Count)
{
tabControl.SelectedIndex = index;
}
}
//alt+d / ctrl+l
if (e.KeyCode == Keys.D || e.KeyCode == Keys.L)
{
txtUrl.Focus();
txtUrl.SelectAll();
}
contextMenuStripHistory.Hide();
};
//keypress
webview2.KeyPress += (s, e) =>
{
this.OnKeyPress(e);
};
tab.Controls.Add(webview2);
url = ConvertToValidUrl(url);
webview2.Source = new Uri(url);
//one webview2 get focus, hide history context menu
webview2.GotFocus += (s, e) =>
{
contextMenuStripHistory.Hide();
};
//WebView2.NavigationCompleted �� is raised when the WebView has completely loaded(body.onload has been raised) or loading stopped with error.
//WebView2.CoreWebView2.DOMContentLoaded �� is raised when the initial html document has been parsed.This aligns with the the document's DOMContentLoaded event in html. (This one is available starting from 1.0.705.50.)
// update progress bar
webview2.CoreWebView2.NavigationStarting += (s, e) =>
{
toolStripProgressBar1.Value = 10;
};
webview2.CoreWebView2.NavigationCompleted += (s, e) =>
{
histories[webview2].Add(
(
webview2.CoreWebView2.DocumentTitle == "" ? webview2.Source.ToString() : webview2.CoreWebView2.DocumentTitle,
webview2.Source.ToString()
)
);
toolStripProgressBar1.Value += 45;
};
//prevent memory leak when tab is closed
webview2.CoreWebView2.DOMContentLoaded += (s, e) =>
{
toolStripProgressBar1.Value += 45;
};
webview2.CoreWebView2.ContentLoading += (s, e) =>
{
toolStripStatusLabel2.Text = "ContentLoaded";
};
//ContextMenuRequested
webview2.CoreWebView2.ContextMenuRequested += (s, args) =>
{
var newItem = webview2.CoreWebView2.Environment.CreateContextMenuItem(
"Open in Default Browser", null, CoreWebView2ContextMenuItemKind.Command);
newItem.CustomItemSelected += (send, ex) =>
{
System.Diagnostics.Process.Start("explorer.exe", args.ContextMenuTarget.PageUri);
};
args.MenuItems.Insert(args.MenuItems.Count, newItem);
};
webview2.CoreWebView2.DocumentTitleChanged += (s, e) =>
{
tab.Text = webview2.CoreWebView2.DocumentTitle;
//if tab is selected, change the form title
if (tabControl.SelectedTab == tab)
{
SetFormTitle(webview2.CoreWebView2.DocumentTitle);
}
};
webview2.CoreWebView2.FaviconChanged += async (s, e) =>
{
//corewebview obj
if (s is not CoreWebView2 coreWebView2)
{
return;
}
Stream iconStream = await coreWebView2.GetFaviconAsync(CoreWebView2FaviconImageFormat.Png);
string iconUrl = coreWebView2.FaviconUri;
imageList1.Images.Add(iconUrl, Image.FromStream(iconStream));
tab.ImageIndex = imageList1.Images.IndexOfKey(iconUrl);
};
//on url change, change the txtUrl.Text
webview2.CoreWebView2.NavigationStarting += (s, e) =>
{
contextMenuStripHistory.Hide();
// only if tab is selected
if (tabControl.SelectedTab == tab)
txtUrl.Text = e.Uri;
};
//on hover, change the status bar text
webview2.CoreWebView2.Settings.IsStatusBarEnabled = false;
webview2.CoreWebView2.StatusBarTextChanged += (s, e) =>
{
string? txt = (s as CoreWebView2)?.StatusBarText;
txt = txt == null ? "" : txt;
toolStripStatusLabel1.Text = txt;
};
//WebResourceRequested
webview2.CoreWebView2.WebResourceRequested += (s, e) =>
{
//log to toolstrip
toolStripStatusLabel1.Text = "Requesting " + e.Request.Uri;
};
//WebResourceResponseReceived
webview2.CoreWebView2.WebResourceResponseReceived += (s, e) =>
{
//log to toolstrip
toolStripStatusLabel2.Text = "Response " + e.Response.StatusCode + ": " + e.Request.Uri;
};
webview2.CoreWebView2.WebMessageReceived += (s, e) =>
{
//log to toolstrip
toolStripStatusLabel1.Text = "WebMessageReceived " + e.WebMessageAsJson;
};
tabControl.SelectedTab = tab;
// No need to call EnsureCoreWebView2Async again as it's already initialized
// add to webview2.CoreWebView2.NewWindowRequested
webview2.CoreWebView2.NewWindowRequested += (s, e) =>
{
e.Handled = true;
NewTab(e.Uri);
};
}
private void NavigateToUrl(string url)
{
// this will navigate to the URL in txtUrl.Text
WebView2 webview2;
if (tabControl.SelectedTab != null && tabControl.SelectedTab.Controls.Count != 0)
{
webview2 = (WebView2)tabControl.SelectedTab.Controls[0];
url = ConvertToValidUrl(url);
webview2.Source = new Uri(url);
}
else
{
NewTab(url);
}
}
private void BtnAddTab_Click(object sender, EventArgs e)
{
NewTab(txtUrl.Text);
}
//convert url into a valid url
static string ConvertToValidUrl(string url)
{
// skip about:blank
if (url == "about:blank")
{
return url;
}
if (!url.StartsWith("http://") && !url.StartsWith("https://"))
{
url = "https://" + url;
}
return url;
}
//fixable url (check if the url is url-like but just without the protocol)
// usage: if the url is not fixable, we do a google search instead of navigating to the url
static bool IsFixableUrl(string url)
{
if (url.Contains(' ') || url.Contains('\n') || url.Contains('\t'))
{
return false;
}
if (url.Contains('.'))
{
return true;
}
return false;
}
private void EnteringUrl(bool isNewTab)
{
string url = txtUrl.Text;
if (IsFixableUrl(url))
{
url = ConvertToValidUrl(url);
txtUrl.Text = url;
}
else
{
txtUrl.Text = "https://www.google.com/search?q=" + url;
}
if (!isNewTab)
{
NavigateToUrl(txtUrl.Text);
}
else
{
NewTab(txtUrl.Text);
}
//focus the webview2
if (tabControl.SelectedTab != null && tabControl.SelectedTab.Controls.Count != 0)
{
WebView2 webview2 = (WebView2)tabControl.SelectedTab.Controls[0];
webview2.Focus();
}
}
private void tsBack_Click(object sender, EventArgs e)
{
// this will navigate back
WebView2 webview2;
if (tabControl.SelectedTab != null && tabControl.SelectedTab.Controls.Count != 0)
{
webview2 = (WebView2)tabControl.SelectedTab.Controls[0];
if (webview2.CoreWebView2.CanGoBack)
{
webview2.CoreWebView2.GoBack();
}
}
}
private void TsRefresh_Click(object sender, EventArgs e)
{
// this will refresh the page
WebView2 webview2;
if (tabControl.SelectedTab != null && tabControl.SelectedTab.Controls.Count != 0)
{
webview2 = (WebView2)tabControl.SelectedTab.Controls[0];
webview2.CoreWebView2.Reload();
}
}
private void toolStripSplitButton1_ButtonClick(object sender, EventArgs e)
{
string helpMessage = "Ctrl+T: New Tab\nCtrl+W: Close Tab\nCtrl+1-9: Switch Tab\nAlt+D/Ctrl+L: Focus URL Bar\nCtrl+Enter/Enter: Load URL\nMiddle Click Tab: Close Tab\nDouble Click Tab: New Tab\nCtrl+R: Refresh\nCtrl+Left/Right: Back/Forward";
MessageBox.Show(helpMessage, "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void toolStripDropDownButton1_Click(object sender, EventArgs e)
{
settings.ShowDialog();
}
private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void closeTabsToolStripMenuItem_Click(object sender, EventArgs e)
{
// this will close all tabs except the below the menu
int index = tabControl.SelectedIndex;
// Close tabs after the selected tab
for (int i = tabControl.TabPages.Count - 1; i > index; i--)
{
// Get the tab to close
TabPage tabToClose = tabControl.TabPages[i];
// Dispose WebView2 before removing the tab
DisposeWebView2InTab(tabToClose);
// Remove the tab
tabControl.TabPages.RemoveAt(i);
}
// Close tabs before the selected tab
for (int i = index - 1; i >= 0; i--)
{
// Get the tab to close
TabPage tabToClose = tabControl.TabPages[i];
// Dispose WebView2 before removing the tab
DisposeWebView2InTab(tabToClose);
// Remove the tab
tabControl.TabPages.RemoveAt(i);
}
}
}
}