-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathBrowserForm.cs
256 lines (209 loc) · 8.43 KB
/
BrowserForm.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
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using CefSharp.DevTools.IO;
using CefSharp.MinimalExample.WinForms.Controls;
using CefSharp.WinForms;
using System;
using System.Net;
using System.Windows.Forms;
namespace CefSharp.MinimalExample.WinForms
{
public partial class BrowserForm : Form
{
#if DEBUG
private const string Build = "Debug";
#else
private const string Build = "Release";
#endif
private readonly string title = "CefSharp.MinimalExample.WinForms (" + Build + ")";
private readonly ChromiumWebBrowser browser;
public BrowserForm()
{
InitializeComponent();
Text = title;
WindowState = FormWindowState.Maximized;
browser = new ChromiumWebBrowser("www.google.com");
toolStripContainer.ContentPanel.Controls.Add(browser);
browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
browser.LoadingStateChanged += OnLoadingStateChanged;
browser.ConsoleMessage += OnBrowserConsoleMessage;
browser.StatusMessage += OnBrowserStatusMessage;
browser.TitleChanged += OnBrowserTitleChanged;
browser.AddressChanged += OnBrowserAddressChanged;
browser.LoadError += OnBrowserLoadError;
var version = string.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}",
Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);
#if NETCOREAPP
// .NET Core
var environment = string.Format("Environment: {0}, Runtime: {1}",
System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(),
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription);
#else
// .NET Framework
var bitness = Environment.Is64BitProcess ? "x64" : "x86";
var environment = String.Format("Environment: {0}", bitness);
#endif
DisplayOutput(string.Format("{0}, {1}", version, environment));
}
private void OnBrowserLoadError(object sender, LoadErrorEventArgs e)
{
//Actions that trigger a download will raise an aborted error.
//Aborted is generally safe to ignore
if (e.ErrorCode == CefErrorCode.Aborted)
{
return;
}
var errorHtml = string.Format("<html><body><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
e.FailedUrl, e.ErrorText, e.ErrorCode);
_ = e.Browser.SetMainFrameDocumentContentAsync(errorHtml);
//AddressChanged isn't called for failed Urls so we need to manually update the Url TextBox
this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = e.FailedUrl);
}
private void OnIsBrowserInitializedChanged(object sender, EventArgs e)
{
var b = ((ChromiumWebBrowser)sender);
this.InvokeOnUiThreadIfRequired(() => b.Focus());
}
private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args)
{
DisplayOutput(string.Format("Line: {0}, Source: {1}, Message: {2}", args.Line, args.Source, args.Message));
}
private void OnBrowserStatusMessage(object sender, StatusMessageEventArgs args)
{
this.InvokeOnUiThreadIfRequired(() => statusLabel.Text = args.Value);
}
private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
SetCanGoBack(args.CanGoBack);
SetCanGoForward(args.CanGoForward);
this.InvokeOnUiThreadIfRequired(() => SetIsLoading(!args.CanReload));
}
private void OnBrowserTitleChanged(object sender, TitleChangedEventArgs args)
{
this.InvokeOnUiThreadIfRequired(() => Text = title + " - " + args.Title);
}
private void OnBrowserAddressChanged(object sender, AddressChangedEventArgs args)
{
this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = args.Address);
}
private void SetCanGoBack(bool canGoBack)
{
this.InvokeOnUiThreadIfRequired(() => backButton.Enabled = canGoBack);
}
private void SetCanGoForward(bool canGoForward)
{
this.InvokeOnUiThreadIfRequired(() => forwardButton.Enabled = canGoForward);
}
private void SetIsLoading(bool isLoading)
{
goButton.Text = isLoading ?
"Stop" :
"Go";
goButton.Image = isLoading ?
Properties.Resources.nav_plain_red :
Properties.Resources.nav_plain_green;
HandleToolStripLayout();
}
public void DisplayOutput(string output)
{
this.InvokeOnUiThreadIfRequired(() => outputLabel.Text = output);
}
private void HandleToolStripLayout(object sender, LayoutEventArgs e)
{
HandleToolStripLayout();
}
private void HandleToolStripLayout()
{
var width = toolStrip1.Width;
foreach (ToolStripItem item in toolStrip1.Items)
{
if (item != urlTextBox)
{
width -= item.Width - item.Margin.Horizontal;
}
}
urlTextBox.Width = Math.Max(0, width - urlTextBox.Margin.Horizontal - 18);
}
private void ExitMenuItemClick(object sender, EventArgs e)
{
browser.Dispose();
Cef.Shutdown();
Close();
}
private void GoButtonClick(object sender, EventArgs e)
{
LoadUrl(urlTextBox.Text);
}
private void BackButtonClick(object sender, EventArgs e)
{
browser.Back();
}
private void ForwardButtonClick(object sender, EventArgs e)
{
browser.Forward();
}
private void UrlTextBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Enter)
{
return;
}
LoadUrl(urlTextBox.Text);
}
private void LoadUrl(string urlString)
{
// No action unless the user types in some sort of url
if (string.IsNullOrEmpty(urlString))
{
return;
}
Uri url;
var success = Uri.TryCreate(urlString, UriKind.RelativeOrAbsolute, out url);
// Basic parsing was a success, now we need to perform additional checks
if (success)
{
// Load absolute urls directly.
// You may wish to validate the scheme is http/https
// e.g. url.Scheme == Uri.UriSchemeHttp || url.Scheme == Uri.UriSchemeHttps
if (url.IsAbsoluteUri)
{
browser.LoadUrl(urlString);
return;
}
// Relative Url
// We'll do some additional checks to see if we can load the Url
// or if we pass the url off to the search engine
var hostNameType = Uri.CheckHostName(urlString);
if (hostNameType == UriHostNameType.IPv4 || hostNameType == UriHostNameType.IPv6)
{
browser.LoadUrl(urlString);
return;
}
if (hostNameType == UriHostNameType.Dns)
{
try
{
var hostEntry = Dns.GetHostEntry(urlString);
if (hostEntry.AddressList.Length > 0)
{
browser.LoadUrl(urlString);
return;
}
}
catch (Exception)
{
// Failed to resolve the host
}
}
}
// Failed parsing load urlString is a search engine
var searchUrl = "https://www.google.com/search?q=" + Uri.EscapeDataString(urlString);
browser.LoadUrl(searchUrl);
}
private void ShowDevToolsMenuItemClick(object sender, EventArgs e)
{
browser.ShowDevTools();
}
}
}