MCPcopy Create free account
hub / github.com/MicrosoftEdge/WebView2Samples / Form1

Class Form1

GettingStartedGuides/WinForms_GettingStarted/Form1.cs:14–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12namespace WinForms_GettingStarted
13{
14 public partial class Form1 : Form
15 {
16 public Form1()
17 {
18 InitializeComponent();
19 this.Resize += new System.EventHandler(this.Form_Resize);
20 webView.NavigationStarting += EnsureHttps;
21 InitializeAsync();
22 }
23
24 private void Form_Resize(object sender, EventArgs e)
25 {
26 webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
27 goButton.Left = this.ClientSize.Width - goButton.Width;
28 addressBar.Width = goButton.Left - addressBar.Left;
29 }
30
31 void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
32 {
33 String uri = args.Uri;
34 if (!uri.StartsWith("https://"))
35 {
36 webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
37 args.Cancel = true;
38 }
39 }
40
41 async void InitializeAsync()
42 {
43 await webView.EnsureCoreWebView2Async(null);
44 webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;
45
46 await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
47 await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
48
49 }
50
51 void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
52 {
53 String uri = args.TryGetWebMessageAsString();
54 addressBar.Text = uri;
55 webView.CoreWebView2.PostWebMessageAsString(uri);
56 }
57
58 private void goButton_Click(object sender, EventArgs e)
59 {
60 if (webView != null && webView.CoreWebView2 != null)
61 {
62 webView.CoreWebView2.Navigate(addressBar.Text);
63 }
64 }
65
66 private void Form1_Load(object sender, EventArgs e)
67 {
68
69 }
70
71 private void webView21_Click(object sender, EventArgs e)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected