Skip to main content

Edit->Find for WebView2 UI Component (WPF/C#/javascript)

I need to implement "Edit->Find" function for a WebView2 UI Component using WPF/C#/javascript... Below you will find two examples: One that is made for a TextBox UI Control called MainWindow1, and the other that is implemented for a WebView2 UI Control that is called MainWindows2. I'm giving both examples because I need to work the same way for each one. The TextBox example is working, but the WebView2 example is missing some javascript code to finish it and maybe requires some tweeting of the C# calls to WebView2.

First, I implemented a "Find Forward" button for a TextBox that I can click multiple times to find the next string matching the search pattern in the textbox. And Here's my XML and C# for it:

MainWindow1 GUI:

Mainwindow1

MainWindow1 XML:

<Window x:Class="WpfApp1.MainWindow1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Loaded="Window_Loaded"
        Title="MainWindow1" Height="450" Width="800">
    <DockPanel LastChildFill="True">
        <StackPanel Orientation="Horizontal"  
               DockPanel.Dock="Top" Background="Aqua">
            <TextBox Name="TboxFind" Width="80" Text="id"/>
            <Button Name="FindForward" Content="FindForward"
                    Click="FindForward_Click"/>
        </StackPanel>

        <TextBox Name="textbox1" VerticalScrollBarVisibility="Auto"/>

    </DockPanel>
</Window>

MainWindow1 C#:

using System.Text.RegularExpressions;
using System.Windows; using System.Windows.Controls;
namespace WpfApp1 {
  public partial class MainWindow1 : Window {
    public MainWindow1() {InitializeComponent();}
    private void Window_Loaded(object sender, RoutedEventArgs e) {
      string text1 = "";
      for (int i = 0; i < 10000; i++) {
        text1 = text1 + "id" + i.ToString() + "\n";}
      textbox1.Text = text1;textbox1.Focus();textbox1.CaretIndex = 0;
    }
    private void TextBoxGotoLine(TextBox textbox1, int linenum) {
      var target_cpos 
         = textbox1.GetCharacterIndexFromLineIndex(linenum);
      var target_char_rect 
         = textbox1.GetRectFromCharacterIndex(target_cpos);
      var first_char_rect = textbox1.GetRectFromCharacterIndex(0);
            textbox1.ScrollToVerticalOffset(target_char_rect.Top 
                  - first_char_rect.Top);
    }
    private void FindForward_Click(object sender, RoutedEventArgs e) {
      string pattern = @"(?i)(" + Regex.Escape(TboxFind.Text) + @")";
      string text1 = textbox1.Text.Substring(
          textbox1.CaretIndex + textbox1.SelectionLength);
      var match1 = Regex.Match(text1, pattern);
      if (match1.Success) {
        textbox1.Focus();
        textbox1.Select(textbox1.CaretIndex 
         + textbox1.SelectionLength 
         + match1.Index, match1.Groups[0].Length);
      } //if
    } //function
}/*class*/  }/*namespace*/ 

The problem I'm having is that I also need this same feature for a WebView2 UI Control.

So I install the WebView2 UI Control:

WebView2 Install:

  • PM > Install-Package Microsoft.Web.WebView2
  • Add to XML: xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
  • using Microsoft.Web.WebView2.Core;

And here's my corresponding XML and C# demo code that should work the same as the first example I have given:

MainWindow2 GUI:

Mainwindow2

MainWindows2 XML:

<Window x:Class="WpfApp1.MainWindow2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wv2
="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"        
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Loaded="Window_Loaded"
Title="MainWindow2" Height="450" Width="800" >
    <DockPanel LastChildFill="True">
        <StackPanel Orientation="Horizontal"  
                 DockPanel.Dock="Top" Background="Aqua">
            <TextBox Name="SearchStr" Width="80" Text="id"/>
            <Button Name="FindForward" 
                 Content="FindForward" Click="FindForward_Click"/>
        </StackPanel>

        <wv2:WebView2 Name="webview2" CoreWebView2InitializationCompleted
          ="webview2_CoreWebView2InitializationCompleted" />

    </DockPanel>
</Window>

MainWindow2 C#:

using System.Windows;  using System.Threading;
using Microsoft.Web.WebView2.Core;
namespace WpfApp1 {
  public partial class MainWindow2 : Window {
  public MainWindow2() {InitializeComponent(); SearchStr.Focus(); }
  private async void Window_Loaded(object sender, RoutedEventArgs e) {
    await webview2.EnsureCoreWebView2Async();   
  }
        
  private void webview2_CoreWebView2InitializationCompleted(
    object sender, CoreWebView2InitializationCompletedEventArgs e)
  {
    string html = "";
    for (int i = 0; i < 100; i++) {
      string id = "id" + i.ToString();
      html = html + "<b>" + id + "</b><br/>";
    }
    webview2.CoreWebView2.NavigateToString(html);
  }
  private async Tasks.Task<string> Find(string pattern) {
    string js = "";
    js = js + "var m1 = document.getElementById(""body"")";
    js = js + "/*... ??? what goes here ??? */";
    // Find and highlight one at a time, and scroll into view ...
    // repeat find from beginning of html body when done ...
    // See MainWindow1 example with TextBox for desired behavior here.
    return await webview2.ExecuteScriptAsync(js);
  }
  private void async FindForward_Click(object s, RoutedEventArgs e) {
    await Find(SearchStr.Text);
  }
}/*class*/  }/*namespace*/

How to use WebBrowser UI Control to do a:

 Menu->Edit->Find "SearchStr1"

When I click FindForward Button? I'm thinking it has something to do with executing Javascript on the DOM? each time the button is pressed?

Via Active questions tagged javascript - Stack Overflow https://ift.tt/K6OlQDJ

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data