Repository navigation
Expand file tree
/
Copy pathMainForm.cs
More file actions
207 lines (182 loc) · 6.45 KB
/
Copy pathMainForm.cs
File metadata and controls
207 lines (182 loc) · 6.45 KB
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
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Text.Json;
namespace EdgeWebViewExample
{
public partial class MainForm : Form
{
private WebView2 webView;
public MainForm()
{
InitializeComponent();
InitializeWebView();
}
private async void InitializeWebView()
{
webView = new WebView2()
{
Dock = DockStyle.Fill
};
this.Controls.Add(webView);
await webView.EnsureCoreWebView2Async();
// Add host object to allow web content to call C# methods
webView.CoreWebView2.AddHostObjectToScript("chrome", new HostObject());
// Handle web messages from JavaScript
webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived;
// Navigate to our HTML content
string htmlContent = GetHtmlContent();
webView.NavigateToString(htmlContent);
}
private void CoreWebView2_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
try
{
string jsonMessage = e.TryGetWebMessageAsString();
// Parse the JSON
var jsonData = JsonSerializer.Deserialize<JsonElement>(jsonMessage);
// Display the received JSON in a message box
string formattedJson = JsonSerializer.Serialize(jsonData, new JsonSerializerOptions { WriteIndented = true });
MessageBox.Show($"Received JSON from WebView:\n\n{formattedJson}", "JSON Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
// You can also access specific properties like:
if (jsonData.TryGetProperty("message", out JsonElement messageElement))
{
string message = messageElement.GetString() ?? "";
Console.WriteLine($"Message: {message}");
}
}
catch (Exception ex)
{
MessageBox.Show($"Error parsing JSON: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private string GetHtmlContent()
{
return @"
<!DOCTYPE html>
<html>
<head>
<title>WebView2 JSON Example</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
background-color: #f0f0f0;
}
button {
padding: 10px 20px;
margin: 10px;
font-size: 16px;
cursor: pointer;
background-color: #007acc;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background-color: #005a9e;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 { color: #333; }
.json-display {
background-color: #f8f8f8;
padding: 15px;
border-radius: 4px;
margin: 10px 0;
font-family: monospace;
border-left: 4px solid #007acc;
}
</style>
</head>
<body>
<div class='container'>
<h1>WebView2 to C# JSON Communication</h1>
<p>Click the buttons below to send different JSON data to C#:</p>
<button onclick='sendSimpleJson()'>Send Simple JSON</button>
<button onclick='sendComplexJson()'>Send Complex JSON</button>
<button onclick='sendUserData()'>Send User Data</button>
<div id='lastSent' class='json-display'></div>
</div>
<script>
function sendSimpleJson() {
const data = {
message: 'Hello from WebView!',
timestamp: new Date().toISOString(),
type: 'simple'
};
sendJsonToHost(data);
}
function sendComplexJson() {
const data = {
message: 'Complex data structure',
timestamp: new Date().toISOString(),
type: 'complex',
user: {
id: 123,
name: 'John Doe',
email: 'john@example.com'
},
items: [
{ id: 1, name: 'Item 1', price: 29.99 },
{ id: 2, name: 'Item 2', price: 39.99 },
{ id: 3, name: 'Item 3', price: 19.99 }
],
settings: {
theme: 'dark',
notifications: true,
language: 'en-US'
}
};
sendJsonToHost(data);
}
function sendUserData() {
const data = {
message: 'User interaction data',
timestamp: new Date().toISOString(),
type: 'user_data',
event: 'button_click',
browserInfo: {
userAgent: navigator.userAgent,
language: navigator.language,
platform: navigator.platform,
cookieEnabled: navigator.cookieEnabled
},
windowSize: {
width: window.innerWidth,
height: window.innerHeight
}
};
sendJsonToHost(data);
}
function sendJsonToHost(data) {
// Display what we're sending
document.getElementById('lastSent').innerHTML =
'<strong>Last sent:</strong><br><pre>' + JSON.stringify(data, null, 2) + '</pre>';
// Send to C# via WebView2
window.chrome.webview.postMessage(JSON.stringify(data));
}
</script>
</body>
</html>";
}
}
// Host object class for additional C# to JavaScript communication if needed
[System.Runtime.InteropServices.ComVisible(true)]
public class HostObject
{
public string GetCurrentTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
public void ShowAlert(string message)
{
MessageBox.Show(message, "Alert from C#", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}