|
|
Posted on 9/27/2022 10:12:31 PM
|
|
|
|

Requirements: How can WebView2 render and display web resources for user actions, how can the web interface communicate with the WinForm application? For example, the web reads hardware information through the application, and the application actively refreshes the content of the web page.
Review:
First, look at the renderings of the communication between the web and the WinForm application, the web sends a message to the application,Invoke the Calculator function that opens the Windows systemAt the same time, the application can also successfully receive messages sent to the web side, as shown in the figure below:
Communication between the host and web content
Hosts and web content can be used to communicate with each other in postMessages, as follows:
- Web content in the WebView2 control can be used to publish a message to the host in window.chrome.webview.postMessage. The host processes the message with any message that registers WebMessageReceived on the host.
- The host publishes messages to the Web content in the WebView2 control CoreWebView2.PostWebMessageAsString using or CoreWebView2.PostWebMessageAsJSON. These messages are captured by the handler added to window.chrome.webview.addEventListener.
Create a new Angular SPA project
This article uses Angular 8.2.14 to create a new web project to demonstrate the communication between the web and the WinForm application.
The code is as follows:
At the same time, modify the app.component.html and app.component.ts files to realize the functions of sending and receiving messages.
app.component.html code is as follows:
app.component.ts code is as follows:
Run the project as shown below:
WinForm application
The host application needs to modify the code as follows:
Modify the WebView2 controlsource attribute is: http://localhost:4200/to launch the application, as shown below:
Finally, try sending messages to each other with the Web and WinForm applications, and you can see that both parties can successfully receive the messages, as shown in the following figure:
(End)
|
Previous:【Performance Optimization】Preconnect, DNS-Prefetch, and Preload features on the front-endNext:[WebView2] (4) Web and WinForm call function methods to each other
|