Update (now the code shows your context menu on right click and hides it when you click anywhere):
You can inject the following javascript
into your webpage (it subscribes to the 'contextmenu
' event and the 'mousedown
' event):
document.addEventListener('contextmenu', function (event)
{
let jsonObject =
{
Key: 'contextmenu',
Value:
{
X: event.screenX,
Y: event.screenY
}
};
window.chrome.webview.postMessage(jsonObject);
});
document.addEventListener('mousedown', function (event)
{
let jsonObject =
{
Key: 'mousedown',
Value:
{
X: event.screenX,
Y: event.screenY
}
};
window.chrome.webview.postMessage(jsonObject);
});
It's easiest to save it in a file (I call it 'Javascript1.js').
To work with the 'CoreWebView2' instance, the WebView2
control must be initialized, subscribing to 'CoreWebView2InitializationCompleted' solves that.
To inject your javascript, you can load it from the file and use AddScriptToExecuteOnDocumentCreatedAsync
to inject it.
You need to disable default context menu. This is done by setting AreDefaultContextMenusEnabled
property to false
.
Then you need to subscribe to the WebMessageReceived
event and handle the two events. To do that, create a structure with a 'Key' and a 'Value' to deserialize the JSON string sent from javascript code.
C# code that shows the whole form with events:
using Newtonsoft.Json;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
struct JsonObject
{
public string Key;
public PointF Value;
}
private async void WebView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView21.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
string script = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, @"Javascript1.js"));
await webView21.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(script);
}
private void WebView21_WebMessageReceived(object sender, Microsoft.Web.WebView2.Core.CoreWebView2WebMessageReceivedEventArgs e)
{
JsonObject jsonObject = JsonConvert.DeserializeObject<JsonObject>(e.WebMessageAsJson);
switch (jsonObject.Key)
{
case "contextmenu":
contextMenuStrip1.Show(Point.Truncate(jsonObject.Value));
break;
case "mousedown":
contextMenuStrip1.Hide();
break;
}
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…