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 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

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings