如何在CefSharp中实现文本搜索

5

我正在使用CefSharp构建一个应用程序,需要为用户提供类似于Google Chrome的文本搜索功能。

有人能帮我实现在CefSharp中的文本搜索吗?

2个回答

9

您可以简单地在表单上添加两个按钮和一个文本框来完成此操作。 第一个按钮用于下一个结果,第二个按钮用于上一个结果,文本框用于搜索提供程序。

在文本框的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事件的代码会搜索该文本,通过使用下一个和上一个按钮,您可以从一个结果导航到另一个。


7
我使用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)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接