If the WebView2 Source is not set, then it draws the rectangle. If we set the Source, then a rectangle is not drawn, because the content is on top of the WebView2 surface.
How do I show a rectangle on top of the content of the WebView2 Control?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webView21.Source = new Uri("https://www.google.com");
}
public void HighlightElementInRectangle(int x, int y, int width, int height)
{
SolidBrush myBrush = new SolidBrush(Color.Red);
Graphics formGraphics;
formGraphics = webView21.CreateGraphics();
Pen pen = new Pen(Color.Red, 2);
formGraphics.DrawRectangle(pen, x, y, width, height);
}
private void webView21_Click(object sender, EventArgs e)
{
HighlightElementInRectangle(18, 111, 319, 20);
}
}
A couple of notes:
[Control].CreateGraphics()(a bad idea in any case) to draw onto the surface of a WebView2 Control. This is just a required container for the actual WebView2 object. You cannot really interact with it.To draw shapes on the rendered HTML page, you can inject a
<canvas>element, then use its 2D context to paint on it.Here, I'm using a static class to store the JavaScripts, then call AddScriptToExecuteOnDocumentCreatedAsync() to inject the script when the page is loaded.
After that, you just need to call ExecuteScriptAsync() to execute functions in the injected script(s).
The JavaScript
drawRectangle()function has some parameters:x,y,widthandheightspecify the size of the shapelinesets the size of the bordercolorspecifies the color of the borderclear(bool) defines whether previous drawings should be erased or notFor the
color, you can use the name of a known color ('red','blue', etc.), or use the HTML format.To translate an ARGB color to HTML, use the ColorTranslator.ToHtml() method.
For example, using a Button Click event to call the script:
This draws a Rectangle
(100, 100, 80, 200)with a border of 4 pixels, using the specified color and erases previous drawings.WebView2 initialization (the Control is named
webViewhere) and scripts injection:The
DrawRectangleOnCanvas()method generates a JavaScript function (drawRectangle()) that paints a rectangular shape on a<canvas>element. It creates one if no element with the specified ID is present.This element is click-through. To make it solid, pass
falseto thecreateOverlayCanvas().The
<canvas>element has fixed size, set to the current window's viewport.Its position can be set as
'fixed'(doesn't scroll) or'absolute'(it scrolls).Modify as required (e.g., if the WebView2 Control can be resized at run-time). In this case, you have to store the
canvasobject, then replace it when the viewport is resized, otherwisecanvas.getContext('2d')returns a new context each time (hence, you cannot persist the drawings, if you decide so).▶ If the syntax here is not available (you didn't specify the .NET version in use), you can store the scripts in a file on disk or in the Project's Resources and load it from there.