赞
踩
今日学习使用Winform操作网页,先从从窗体内嵌一个浏览器开始吧:
文章提供测试代码讲解、测试效果图、整体测试工程下载
目录
CefSharp是一个基于Chromium Embedded Framework(CEF)的.NET封装库,它允许在C#应用程序中嵌入Chromium浏览器。CefSharp的主要用途是嵌入了第三方应用以实现浏览器相关的功能,例如显示网页、执行JavaScript代码、处理用户输入等。CefSharp可以用于开发各种类型的应用程序,如网页浏览器、网页编辑器、Web应用程序等。它提供了丰富的API和功能,使开发人员能够轻松地与Chromium浏览器进行交互和控制。CefSharp是Cef的C#版本,让Chromium浏览器也可嵌入WinForms和WPF中。
简言之,Cef支持HTML,CSS,JavaScript,可以在CS中像web网站那样操作。与winform中自带的webBrowser一样,只是CefSharp是独立的,基于Chrome浏览器,而webBrowser基于IE浏览器。
首先建立一个winform程序,项目选择.NET Framework4.8框架
在Nuget中,下载cefsharp:
没有放置别的控件,仅仅一个Tabcontrol而已:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
-
- using CefSharp;
- using CefSharp.WinForms;
-
-
- namespace WpfWithCefSharpDemo
- {
- public partial class Form1 : Form
- {
- public ChromiumWebBrowser chromeBrowser;
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- InitializeChromium(GetTabPage1());//初始化
-
- }
-
- public TabPage GetTabPage1()
- {
- return tabPage1;
- }
-
- public void InitializeChromium(TabPage tabPage1)
- {
- CefSettings settings = new CefSettings();
- settings.Locale = "zh-CN";
- // Initialize cef with the provided settings
- Cef.Initialize(settings);
- // Create a browser component
- chromeBrowser = new ChromiumWebBrowser("https://www.bilibili.com/");
- // Add it to the form and fill it to the form window.
- //this.Controls.Add(chromeBrowser);
- //chromeBrowser.Dock = DockStyle.Fill;
-
- // 确保tabPage1已经被添加到tabControl中
- // 如果还没有,你需要先创建并添加它:tabControl.TabPages.Add("My Tab", "tabPage1");
- // Add the browser to the TabPage's Controls collection, not the Form's
- tabPage1.Controls.Add(chromeBrowser); // 假设tabPage1是TabControl中的一个TabPage
- chromeBrowser.Dock = DockStyle.Fill; // Fill the entire TabPage with the browser
- }
-
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- Cef.Shutdown();
- }
-
- }
-
- }

可以在框出的代码部分更改你要访问的网页网址:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。