首页 > 其他分享 >WPF项目中使用WInform版本的 ChromiumWebBrowser控件嵌套网页 解决中文输入法候选框定位问题

WPF项目中使用WInform版本的 ChromiumWebBrowser控件嵌套网页 解决中文输入法候选框定位问题

时间:2023-05-06 10:01:28浏览次数:64  
标签:控件 输入法 fs 定位问题 sw new webView public browser

创建一个用户控件,后台代码:

 public partial class CefControl : UserControl
    {
        ChromiumWebBrowser webView = null;
        public CefControl()
        {
            InitializeComponent();


            if (!CefSharp.Cef.IsInitialized)
            {
                var settings = new CefSettings() { RemoteDebuggingPort = 8088 };
                {
                    //By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
                    var CachePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
                };
                settings.Locale = "zh-CN";
                settings.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.2; zh-CN) AppleWebKit/533+ (KHTML, like Gecko)";
                settings.CefCommandLineArgs.Add("enable-media-stream", "1");
                settings.CefCommandLineArgs.Add("disable-gpu", "1"); // 禁用gpu  
                Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

            }

            webView = new ChromiumWebBrowser("https://www.baidu.com/");
            this.Controls.Add(webView);
            webView.Dock = DockStyle.Fill;
            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            //注册js对象
            JSHelperChrome helper = new JSHelperChrome();
            helper.OpeningFile += Helper_OpeningFile;
            BindingOptions bindingOption = new BindingOptions
            {
                CamelCaseJavascriptNames = false,
                Binder = BindingOptions.DefaultBinder.Binder,
            };
            webView.JavascriptObjectRepository.Register("JSBridge", helper, isAsync: false, options: bindingOption);
            //按F12显示调试工具
            webView.KeyboardHandler = new CEFKeyBoardHander();
            webView.FrameLoadEnd += Webview_FrameLoadEnd;
            webView.FrameLoadStart += WebView_FrameLoadStart;
        }

        private void WebView_FrameLoadStart(object sender, FrameLoadStartEventArgs e)
        {
        }

        private void Webview_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            if (e.Frame.IsMain)
            {
                this.webView.ExecuteScriptAsync(@"
                //设置test对象 这样前段页面就能拿到window.test这个参数信息
                window.test = JSBridge;
                //alert('test!');
                ");
            }
        }
        private void Helper_OpeningFile()
        {
        }

        public void WriteLog(string msg)
        {
            FileStream fs = null;
            StreamWriter sw = null;
            try
            {
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
                if (!basePath.EndsWith("/"))
                    basePath += "/";

                var logFile = basePath + "Log";
                if (!File.Exists(logFile))
                    File.CreateText(logFile).Dispose();

                fs = new FileStream(logFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                sw = new StreamWriter(fs, Encoding.UTF8);

                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff"));
                sw.WriteLine(msg);
                sw.WriteLine("-------------------------------------");
                sw.Flush();
                fs.Flush();
            }
            catch { }
            finally
            {
                if (sw != null)
                {
                    try { sw.Close(); sw.Dispose(); } catch { }
                }
                if (fs != null)
                {
                    try { fs.Close(); fs.Dispose(); } catch { }
                }
            }
        }
    }

    public class CEFKeyBoardHander : IKeyboardHandler
    {
        public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
        {
            if (type == KeyType.KeyUp && Enum.IsDefined(typeof(Keys), windowsKeyCode))
            {
                var key = (Keys)windowsKeyCode;
                switch (key)
                {
                    case Keys.F12:
                        browser.ShowDevTools();
                        break;

                    case Keys.F5:

                        if (modifiers == CefEventFlags.ControlDown)
                        {
                            browser.Reload(true); //强制忽略缓存
                        }
                        else
                        {
                            browser.Reload();
                        }
                        break;
                }
            }
            return false;
        }

        public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
        {
            return false;
        }
    }
    public class JSHelperChrome
    {

        public event Action OpeningFile;

        public JSHelperChrome()
        {

        }

        public void OpenFile(string cloudFileUrl)
        {
            OpeningFile?.Invoke();
        }
    }

 

创建一个WPF Window界面

<Window x:Class="WpfApp1.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:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"  WindowState="Maximized" 
        Title="MainWindow" Height="450" Width="800" WindowStyle="SingleBorderWindow">
    <Grid x:Name="root">
        <ContentControl Name="contextHolder" Grid.Row="1"    />
    </Grid>
   

 

后台使用:

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            WindowsFormsHost browser = new WindowsFormsHost();
            browser.Child = new CefControl();
            contextHolder.Content = browser;
       
        }
    }

 

标签:控件,输入法,fs,定位问题,sw,new,webView,public,browser
From: https://www.cnblogs.com/anjingdian/p/17376093.html

相关文章

  • 界面控件DevExpress WPF富文本编辑器,让系统拥有Word功能(二)
    DevExpressWPF控件的富文本编辑器允许开发者将文字处理功能集成到下一个WPF项目中,凭借其全面的文本格式选项、邮件合并以及丰富的终端用户选项集合,可以轻松地提供MicrosoftWord功能。DevExpressWPF拥有120+个控件和库,将帮助您交付满足甚至超出企业需求的高性能业务应用程序。......
  • 第5-0讲,Text 文本控件
    Entry只能输入一行文字,如果想要输入多行文字,需要使用Text文本控件importtkinterastkfromtkinterimportmessagebox#创建窗体window=tk.Tk()#设置窗体的标题window.title('多行输入-text')#设置窗体的大小window.geometry('300x200')#创建textcontext=tk.Text......
  • 第4-0讲,entry 输入控件
    当你需要在页面上输入信息时,比如用户名和密码,那么你需要使用Entry控件importtkinterastkfromtkinterimportmessagebox#创建窗体window=tk.Tk()#设置窗体标题window.title("标签属性")#设置窗体的图标window.iconbitmap('../images/米饭.ico')#设置窗体大小windo......
  • 【VBA】树控件TreeView的学习(一)
    哈喽,手机边亲爱的你还好吗?我是默默给大家分享Access知识的will。大家2022年快乐,从今天开始我们来讲一下树控件。树控件在我们的开发中是经常用的到的控件也是一个重点,我会从最简单的讲起,一点点,一点点的加上难度,最后我们把BOM挂到树上,顺便讲一下BOM。我会先发一篇文章再出一个视频。......
  • WPF Thumb 滑块控件踩坑
    最近在做一个仿手机选择时间的控件,如下图,选用了Thumb滑块控件做上下滑动的功能。订阅了 Thumb_OnDragStarted、Thumb_DragDelta和Thumb_DragCompleted的事件,做一些业务逻辑 发现问题:在我们普通pc电脑上,滑块的Thumb_DragDelta和Thumb_DragCompleted的e.VerticalChange......
  • [小工具] 五笔输入法
    之前用的光速五笔,有时候竟然要用掉100多M的内存。也不知道在弄什么玩意。现在换成了极品五笔。有一个小技巧可以使用:Ctrl+~的造词功能。按Ctrl+~造词后再按Ctrl+~保存。下面这个承诺很不错.郑重承诺自2001年五月问世,极品五笔已走过十个春秋了,在今后的十年里,极品......
  • 使用Python实现Ubuntu搜狗输入法的安装
    Ubuntu搜狗输入法在每次安装后都需要重新配置,非常繁琐。我们可以使用Python的subprocess模块来实现。以下是示例代码,它使用了subprocess模块中的check_call()函数来执行安装命令:importsubprocesssubprocess.check_call(['sudo','add-apt-repository','-y','ppa:fcitx-team/nig......
  • MFC-NM_CLICK鼠标左键点击CListCtrl控件消息
    NM_CLICK是鼠标左键点击CListCtrl控件客户区时激发的消息添加消息函数选中控件-->          ......
  • 迷你轻量级全方向完美滑动处理侧滑控件SlideLayout
    纯手工超级迷你轻量级全方向完美滑动处理侧滑控件(比官方supportv4包SlidingPaneLayout控件更加Q迷你,累计代码不足300行),支持上下左右有各种侧拉,可配置侧拉松手临界距离,支持单独使用、ListView、GridView、RecycleView、ScrollView、ViewPager等各种嵌套(作为item使用或......
  • MFC-SetImageList给列表视图控件设置图像列表
     CImageList*pImageList;HBITMAPhbmp1;CBitmap*pBitmap1;HBITMAPhbmp2;CBitmap*pBitmap2;HBITMAPhbmp3;CBitmap*pBitmap3;HBITMAPhbmp4;CBitmap*pBitmap4; pImageList=newCImageList();//创建一个CImageList类的指针变量pImageList->Cr......