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