当前位置:网站首页>C # make a simple browser
C # make a simple browser
2022-07-23 13:42:00 【Walk in loosing】
Do you want to have your own browser ? Do you want to realize browser customization ?
Isn't it so difficult ?
Is it right to learn c++ All kinds of bottom drawings ?
NO, It's not that complicated , With Google open source chromium It's much easier for the kernel to package a browser .
But that's c++ The kernel of , Don't you want to learn c++, Look at the kernel documentation ?
NO, It's not that complicated . There are open source C# project , packing chromium The kernel is C# Dynamic library , Yes C# Just quote dll Then there is a common control that can be used by dragging .
effect :
The downloaded package only needs C#winfrom Engineering citation cwber.dll You can use browser controls 

Then you can do the most stupid winform operation , Drag the control to the page to realize a browser .
The code sets its URL You can use it 
The above is the traditional way , Download dynamic libraries and dependent packages on your official website . This time nuget Make a new browser example by referencing packages .
1. So let's create one .net4.6 engineering , Right click - Reference addition buget Search in the bag cefsharp install 
2. Give the window Load Event plus the following code test , So you get a no url Input browser 

3. Then drag two panels and one... To the page url Input text box 
4. Then change the code to realize the carriage return event in the text box , In this way, I customized a simple browser for myself
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
namespace MyBrowser
{
public partial class FrmMain : Form
{
/// <summary>
/// Browser object
/// </summary>
ChromiumWebBrowser chromeBrowser = null;
public FrmMain()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
txtPath.Text = "https://www.baidu.com";
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
chromeBrowser = new ChromiumWebBrowser(txtPath.Text);
panel2.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
}
/// <summary>
/// Input box key
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode==Keys.Enter&& txtPath.Text!="")
{
chromeBrowser.LoadUrl(txtPath.Text);
}
}
}
}
5. effect 


enough easy Well , There are no comments 50 That's ok C# Just customize a browser . You can also pack webkit Kernel .
Play with other customization
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using Sashulin;
using Sashulin.Core;
using Sashulin.common;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace LISBrowser
{
/// <summary>
/// Execute command delegation
/// </summary>
/// <param name="result"></param>
public delegate void ExcCodeDelegate(string code);
///<summary NoteObject="Class">
/// [ Function description :LIS Browser home page ] <para/>
/// [ The creator :zlz] <para/>
/// [ Creation time :2015 year 5 month 24 Japan ] <para/>
///< explain >
/// [ explain :LIS Browser home page ]<para/>
///</ explain >
///< Modify the record >
/// [ Modification time : Time of this modification ]<para/>
/// [ Modify the content : The content of this revision ]<para/>
///</ Modify the record >
///< Modify the record >
/// [ Modification time : Time of this modification ]<para/>
/// [ Modify the content : The content of this revision ]<para/>
///</ Modify the record >
///</summary>
public partial class LBMainForm : Form
{
/// <summary>
/// IP Information
/// </summary>
private string IPStr = "";
/// <summary>
/// Heading information
/// </summary>
private string TitleStr = "";
// Is it full screen
private string FullScreen = ConfigurationManager.AppSettings["FullScreen"];
// Display hardware information
private string ShowHardware = ConfigurationManager.AppSettings["ShowHardware"];
/// <summary>
/// Constructors
/// </summary>
public LBMainForm()
{
InitializeComponent();
// Get configured url
string url = ConfigurationManager.AppSettings["StartUrl"];
if (FullScreen == "1")
{
this.FormBorderStyle = FormBorderStyle.None;
}
if (FullScreen == "2")
{
this.ControlBox = false;
this.MinimizeBox = false;
this.MaximizeBox = false;
}
if (ShowHardware == "1" || ShowHardware == "2" || ShowHardware == "3")
{
IPStr = " Current equipment number :" + GetIpv4Str();
this.Text = " Current equipment number :" + GetIpv4Str() + ", Starting time :" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
timerMian.Enabled = true;
}
// Check whether the is configured
if (url == null || url == "")
{
MessageBox.Show(" Please use the program with the same name config File configuration LIS The startup path of the system !");
return;
}
// Open the start page
OpenPage(url, null, false);
// Set thread
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// Get the current machine's ip4 strand
/// </summary>
/// <returns></returns>
private string GetIpv4Str()
{
IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in arrIPAddresses)
{
if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
{
return ip.ToString();
}
}
return string.Empty;
}
/// <summary>
/// Change Icon
/// </summary>
private void ChangeIconByName(string name)
{
this.Icon = new Icon(Application.StartupPath + "\\" + name + ".ico");
}
/// <summary>
/// Title Change Event
/// </summary>
/// <param name="sender"> Event trigger </param>
/// <param name="e"> Parameters </param>
private void chromeWebBrowser_BrowserTitleChange(object sender, TitleEventArgs e)
{
// Display hardware information
string ShowHardware = ConfigurationManager.AppSettings["ShowHardware"];
if (ShowHardware == "1")
{
return;
}
if (ShowHardware == "2" || ShowHardware == "3")
{
TitleStr = e.Title;
return;
}
if (e.Title != "about:blank")
{
this.Text = e.Title;
}
}
/// <summary>
/// entrust
/// </summary>
/// <param name="url">url</param>
/// <param name="request"> Request object , Not empty </param>
/// <param name="isNewPage"> Whether to open a new page </param>
delegate void NewPageListener(string url, object request, bool isNewPage);
/// <summary>
/// Pop up new window event
/// </summary>
/// <param name="sender"> Event trigger </param>
/// <param name="e"> Parameters </param>
private void chromeWebBrowser_BrowserNewWindow(object sender, NewWindowEventArgs e)
{
if (this.InvokeRequired)
{
NewPageListener a = new NewPageListener(OpenPage);
this.Invoke(a, new object[] {
e.NewUrl, e.Request, true });
}
else
{
OpenPage(e.NewUrl, e.Request, true);
}
}
/// <summary>
/// Open page
/// </summary>
/// <param name="url">url</param>
/// <param name="req"> Request object , If not, it is empty </param>
/// <param name="isNewPage"> Whether to create a new page </param>
private void OpenPage(string url, object req, bool isNewPage)
{
// Set the object
CSharpBrowserSettings settings = new CSharpBrowserSettings();
settings.Locale = "zh-CN";
// edition
settings.UserAgent = "Mozilla/5.0 (Windows; 7 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19";
// Cache path
settings.CachePath = @"C:\temp\caches";
// Create a browser object
ChromeWebBrowser browser = new ChromeWebBrowser();
// The binding event
browser.BrowserNewWindow += new NewWindowEventHandler(chromeWebBrowser_BrowserNewWindow);
// Bind title change event
browser.BrowserTitleChange += new TitleChangeEventHandler(chromeWebBrowser_BrowserTitleChange);
// Initialize settings
browser.Initialize(settings);
// If it's not a new page
if (isNewPage == false)
{
this.Controls.Clear();
this.Controls.Add(browser);
// verification
browser.Validate();
// Set fill
browser.Dock = DockStyle.Fill;
if (!url.Contains("&"))
{
browser.OpenUrl(url);
}
else
{
browser.OpenUrl(req);
}
// Set up Cookie route
browser.SetCookiePath("c:\\temp");
}
// Create and pop up a new page
else
{
LBDialogForm form = new LBDialogForm();
form.OpenPage(url, req, false);
form.Show();
}
}
/// <summary>
/// replica catalog
/// </summary>
/// <param name="srcPath"> The source path </param>
/// <param name="aimPath"> The target path </param>
private void CopyDir(string srcPath, string aimPath)
{
try
{
// Check whether the target directory ends with the directory split character. If not, add
if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
aimPath += System.IO.Path.DirectorySeparatorChar;
}
// Judge whether the target directory exists. If it does not exist, create a new directory
if (!System.IO.Directory.Exists(aimPath))
{
System.IO.Directory.CreateDirectory(aimPath);
}
// Get the file list of the source directory , It contains an array of files and directory paths
// If you point to copy The file below the target file does not contain the directory. Please use the following method
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
// Traverse all files and directories
foreach (string file in fileList)
{
// First, treat it as a directory. If there is a directory, it will be recursive Copy Files under this directory
if (System.IO.Directory.Exists(file))
{
CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
}
// Otherwise directly Copy file
else
{
System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
}
}
}
catch (Exception e)
{
throw;
}
}
/// <summary>
/// Timer Functions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timerMian_Tick(object sender, EventArgs e)
{
if (ShowHardware == "2")
{
this.Text = TitleStr + IPStr + ", current time :" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
else if (ShowHardware == "3")
{
this.Text = IPStr + ", current time :" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + TitleStr;
}
else
{
this.Text = IPStr + ", current time :" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
}
/// <summary>
/// Prohibit double clicking the title bar event
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
if (FullScreen == "2")
{
// Double click on the title bar 、 System messages for mobile forms
if (m.Msg != 0xA3 && m.Msg != 0x0003 && m.WParam != (IntPtr)0xF012)
{
base.WndProc(ref m);
}
}
else
{
base.WndProc(ref m);
}
}
}
}
The advantage is that it's simple 、 Customizable . The disadvantage is that it is not easy to use the latest browser , The debugging function is weak . Then the kernel rendering is slow in some operating systems . Can't keep up with the latest w3c standard .
边栏推荐
- ROS2自学笔记:Gazebo物理仿真平台
- [visual scheduling software] Shanghai daoning brings netronic downloads, trials and tutorials to SMB organizations
- 高性能JVM的参数
- About this pointer
- [jzof] 07 rebuild binary tree
- GLIB-CRITICAL g_file_test:assertion ‘filename != null‘ failed
- JVM detailed parsing
- Shell operator, $((expression)) "or" $[expression], expr method, condition judgment, test condition, [condition], comparison between two integers, judgment according to file permission, judgment accor
- Notes du jour 7
- Feynman learning method (redis summary)
猜你喜欢

0722~ thread pool extension

Beifu PLC and C transmit string type through ads communication

高性能JVM的参数

Introduction to radar part vii 3 formation and processing of SAR image

Kept dual machine hot standby

In depth interpretation of EVM's ecological Empire

Target segmentation for 10000 frames of video, with less than 1.4GB of video memory | eccv2022

php连接sql server

The current situation of the industry is disappointing. After working, I returned to UC Berkeley to study for a doctoral degree

第二章关系数据库课后习题
随机推荐
ES6——周考题
动态规划每日一练(1)
Database view detailed exploration
C language insert sort (direct insert sort)
数据库-视图详探
"100 Android interview questions" I brushed angrily for Dachang
【PART 2】OAK-D+TurtleBot3机器人项目全解析
Day 11 notes
深入解读 EVM 的生态帝国
Ros2 self study notes: URDF robot modeling
Wechat applet -- dynamically set the navigation bar color
Running matlab program on GPU
Remote editing and debugging with vscode
vs2019:constexpr 函数“qCountLeadingZeroBits”不能生成常量表达式
2. Les règles quantitatives
Probability meditation: 2. The quantitative rules
【cocos creator】spine动画,监听播放结束
Course design - push box C (win form)
Target segmentation for 10000 frames of video, with less than 1.4GB of video memory | eccv2022
了解canvas