簡體   English   中英

如何在cefSharp中實現文本搜索

[英]How to implement Text Search in cefSharp

我正在使用cefSharp構建和應用程序。 現在我需要像Google Chrome一樣為用戶提供文本搜索功能。 任何人都可以幫助我在cefSharp實現文本搜索。

您只需在表單上添加兩個buttons和一個textbox 下一個結果的第一個buttons ,上一個結果的第二個buttons和搜索文本提供者的textbox

在文本框的KeyUp事件下運行代碼

if (tosBrowserSearchTxt.Text.Length <= 0)
{
    //this will clear all search result
    webBrowserChromium.StopFinding(true);
}
else
{
    webBrowserChromium.Find(0, tosBrowserSearchTxt.Text, true, false,false);
}

在下一個按鈕上單擊下面的代碼運行

webBrowserChromium.Find(0, tosBrowserSearchTxt.Text, true, false, false); 

在上一個按鈕上單擊代碼運行

webBrowserChromium.Find(0, tosBrowserSearchTxt.Text, false, false, false);

當用戶在文本框中鍵入任何字符時,KeyUp事件的代碼將搜索該文本,通過使用下一個和上一個按鈕,您可以從一個結果導航到另一個結果。

我使用CefSharp 47.0.3構建了這個演示應用程序,希望這正是您所需要的。

風景:

<Window x:Class="CefSharpSearchDemo.MainWindow"
        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:wpf="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:cefSharpSearchDemo="clr-namespace:CefSharpSearchDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        d:DataContext="{d:DesignInstance {x:Type cefSharpSearchDemo:MainWindowViewModel}}">
    <DockPanel>
        <DockPanel DockPanel.Dock="Top">
            <Button Content="Next" DockPanel.Dock="Right" Command="{Binding ElementName=SearchBehavior, Path=NextCommand}" />
            <Button Content="Previous" DockPanel.Dock="Right" Command="{Binding ElementName=SearchBehavior, Path=PreviousCommand}"  />
            <TextBox DockPanel.Dock="Right" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"></TextBox>
        </DockPanel>

        <wpf:ChromiumWebBrowser x:Name="wb" DockPanel.Dock="Bottom"
                                Address="http://stackoverflow.com">
            <i:Interaction.Behaviors>
                <cefSharpSearchDemo:ChromiumWebBrowserSearchBehavior x:Name="SearchBehavior" SearchText="{Binding SearchText}" />
            </i:Interaction.Behaviors>
        </wpf:ChromiumWebBrowser>
    </DockPanel>
</Window>

視圖的代碼隱藏:

namespace CefSharpSearchDemo
{
    using System.Windows;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new MainWindowViewModel();
        }
    }
}

視圖模型:

namespace CefSharpSearchDemo
{
    using System.ComponentModel;
    using System.Runtime.CompilerServices;

    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _searchText;

        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value;
                NotifyPropertyChanged();
            }
        }

        protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

而現在是重要的一部分。 正如您在視圖中看到的那樣, ChromiumWebBrowser附加了一個行為:

namespace CefSharpSearchDemo
{
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Interactivity;
    using CefSharp;
    using CefSharp.Wpf;

    public class ChromiumWebBrowserSearchBehavior : Behavior<ChromiumWebBrowser>
    {
        private bool _isSearchEnabled;

        public ChromiumWebBrowserSearchBehavior()
        {
            NextCommand = new DelegateCommand(OnNext);
            PreviousCommand = new DelegateCommand(OnPrevious);
        }

        private void OnNext()
        {
            AssociatedObject.Find(identifier: 1, searchText: SearchText, forward: true, matchCase: false, findNext: true);
        }

        private void OnPrevious()
        {
            AssociatedObject.Find(identifier: 1, searchText: SearchText, forward: false, matchCase: false, findNext: true);
        }

        protected override void OnAttached()
        {
            AssociatedObject.FrameLoadEnd += ChromiumWebBrowserOnFrameLoadEnd;
        }

        private void ChromiumWebBrowserOnFrameLoadEnd(object sender, FrameLoadEndEventArgs frameLoadEndEventArgs)
        {
            _isSearchEnabled = frameLoadEndEventArgs.Frame.IsMain;

            Dispatcher.Invoke(() =>
            {
                if (_isSearchEnabled && !string.IsNullOrEmpty(SearchText))
                {
                    AssociatedObject.Find(1, SearchText, true, false, false);
                }
            });
        }

        public static readonly DependencyProperty SearchTextProperty = DependencyProperty.Register(
            "SearchText", typeof(string), typeof(ChromiumWebBrowserSearchBehavior), new PropertyMetadata(default(string), OnSearchTextChanged));

        public string SearchText
        {
            get { return (string)GetValue(SearchTextProperty); }
            set { SetValue(SearchTextProperty, value); }
        }

        public static readonly DependencyProperty NextCommandProperty = DependencyProperty.Register(
            "NextCommand", typeof (ICommand), typeof (ChromiumWebBrowserSearchBehavior), new PropertyMetadata(default(ICommand)));

        public ICommand NextCommand
        {
            get { return (ICommand) GetValue(NextCommandProperty); }
            set { SetValue(NextCommandProperty, value); }
        }

        public static readonly DependencyProperty PreviousCommandProperty = DependencyProperty.Register(
            "PreviousCommand", typeof (ICommand), typeof (ChromiumWebBrowserSearchBehavior), new PropertyMetadata(default(ICommand)));

        public ICommand PreviousCommand
        {
            get { return (ICommand) GetValue(PreviousCommandProperty); }
            set { SetValue(PreviousCommandProperty, value); }
        }

        private static void OnSearchTextChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var behavior = dependencyObject as ChromiumWebBrowserSearchBehavior;

            if (behavior != null && behavior._isSearchEnabled)
            {
                var newSearchText = dependencyPropertyChangedEventArgs.NewValue as string;

                if (string.IsNullOrEmpty(newSearchText))
                {
                    behavior.AssociatedObject.StopFinding(true);
                }
                else
                {
                    behavior.AssociatedObject.Find(1, newSearchText, true, false, false);
                }
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.FrameLoadEnd -= ChromiumWebBrowserOnFrameLoadEnd;
        }
    }
}

DelegateCommand的次要附加代碼:

namespace CefSharpSearchDemo
{
    using System;
    using System.Windows.Input;

    public class DelegateCommand : ICommand
    {
        private readonly Action _action;

        public DelegateCommand(Action action)
        {
            _action = action;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            _action();
        }

        public event EventHandler CanExecuteChanged;
    }
}

生成的應用程序頂部有一個TextBox ,旁邊標有“Previous”和“Next”的兩個按鈕。

主要區域是加載http://www.stackoverflow.com的CefSharp瀏覽器。

您可以輸入TextBox ,它將在瀏覽器中搜索(並突出顯示點擊的滾動條,就像在Chrome中一樣)。 然后,您可以按“下一個/上一個”按鈕循環點擊。

我希望這有助於開發自己的解決方案。

所有這些都說,讓我注意下次如果你問一個問題,實際上提供了一些你嘗試過的代碼,或者嘗試提出一個更具體的問題,因為這對於這個網站來說可能太寬泛了。 無論如何,我把它留在這里,也許其他人會發現它也很有用。

重要的一課: ChromiumWebBrowser上有一些可用於實現搜索功能的方法(即: FindStopFinding )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM