CefSharp winform谷歌浏览器控件禁止弹窗与右键
作者:admin 日期:2024-01-14
虽然能用CefSharp将web应用嵌入到窗体程序,但遇到<a >标签(_blank)会弹出一个窗口,而且在任意位置可以弹出右键菜单,
需要解决这个问题才像一个真正的客户端软件。
不弹子窗体
控制弹窗的接口是ILifeSpanHandler,并实现OnBeforePopup方法。如下:
定义LifeSpanHandler类:
- using CefSharp;
- using CefSharp.WinForms;
- namespace CefTest
- {
- internal class LifeSpanHandler : ILifeSpanHandler
- {
- //弹出前触发的事件
- public bool OnBeforePopup(IWebBrowser webBrowser, IBrowser browser, IFrame frame, string targetUrl,
- string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures,
- IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
- {
- //使用源窗口打开链接,取消创建新窗口
- newBrowser = null;
- var chromiumWebBrowser = (ChromiumWebBrowser)webBrowser;
- chromiumWebBrowser.Load(targetUrl);
- return true;
- }
- public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
- {
- }
- public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
- {
- return true;
- }
- public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
- {
- }
- }
- }
调用方式
- using CefSharp;using CefSharp.WinForms;
- namespace LawSever
- {
- public partial class frmweb : Form
- {
- public frmweb()
- {
- InitializeComponent();
- InitBrowser();
- }
- public ChromiumWebBrowser browser;
- public void InitBrowser()
- { //Cef.Initialize(new CefSettings());//亲测这句代码 可不执行 也好用
- browser = new ChromiumWebBrowser("https://ai.12348.gov.cn/pc/");
- browser.LifeSpanHandler = new LifeSpanHandler();//超链接不弹新窗体
- this.panel1.Controls.Add(browser);//panel
- }
- }
禁用右键
禁用右键的接口是IContextMenuHandler,并实现OnBeforeContextMenu 方法。如下:
定义MenuHandler类:
- using CefSharp;
- namespace CefTest
- {
- internal class MenuHandler : IContextMenuHandler
- {
- public void OnBeforeContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters,
- IMenuModel model)
- {
- model.Clear();
- }
- public bool OnContextMenuCommand(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters,
- CefMenuCommand commandId, CefEventFlags eventFlags)
- {
- return false;
- }
- public void OnContextMenuDismissed(IWebBrowser webBrowser, IBrowser browser, IFrame frame)
- {
- }
- public bool RunContextMenu(IWebBrowser webBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters,
- IMenuModel model, IRunContextMenuCallback callback)
- {
- return false;
- }
- }
- }
调用方式:
- ChromeBrowser.MenuHandler = new MenuHandler();
c# 保存文本文件
作者:admin 日期:2022-11-09
- private void btSave_Click(object sender, EventArgs e) //保存txt文件
- {
- saveFileDialog1.Filter = ("文本文件(*.txt)|*.txt"); //创建一个筛选器
- if (saveFileDialog1.ShowDialog() == DialogResult.OK) //判断按下的是保存还是取消
- {
- string path = saveFileDialog1.FileName; //获得文件名和路径
- using (StreamWriter sw = new StreamWriter(path, false)) //保存文件到指定路径
- {
- sw.WriteLine(txtNote.Text);
- }
- }
- private void btOpen_Click(object sender, EventArgs e) //打开txt文件
- {
- openFileDialog1.Filter = ("文本文件(*.txt)|*.txt"); //创建一个筛选器
- if (openFileDialog1.ShowDialog() == DialogResult.OK) //判断按下的是打开还是取消
- {
- string path = openFileDialog1.FileName; //获得文件名和路径
- using (StreamReader sr = new StreamReader(path, Encoding.UTF8)) //打开文件
- {
- txtNote.Text = sr.ReadToEnd();
- }
- }
- }
1、使用的命名空间是:System.IO;
2、用来将字符串写入文件。
常用属性:
AutoFlush:获取或设置一个值,该值指示是否 System.IO.StreamWriter 将其缓冲区刷新到基础流在每次调用后 System.IO.StreamWriter.Write(System.Char)。
Encoding:获取在其中写入输出的 System.Text.Encoding。
常用方法:
WriteLine():写入文件,并且换行。
Write():多种重写方式,具体可以查VS文档。
Dispose():释放由 System.IO.StreamWriter 占用的非托管资源,还可以另外再释放托管资源。
Flush():清理当前写入器的所有缓冲区,并使所有缓冲数据写入基础流。
Close():关闭流。
使用简单示例:
- string str = "Hello";
- string path = @"D:dataWrite.txt";
- // path:写入文件的路径,append:true 若要将数据追加到该文件; false 覆盖该文件。 如果指定的文件不存在,该参数无效,且构造函数将创建一个新文件。
- StreamWriter sr = new StreamWriter(path,true,Encoding.Default); // 保留文件原来的内容
- sr.WriteLine(str);
- sr.Flush(); // 清空缓存
- sr.WriteLine(str);
C#遍历浏览某个文件夹下的所有文件
作者:admin 日期:2022-11-09
C#遍历浏览某个文件夹下的所有文件,方法如下:
- //C#遍历指定文件夹中的所有文件
- DirectoryInfo TheFolder = new DirectoryInfo(path);
- if (!TheFolder.Exists)
- return;
- //遍历文件
- foreach (FileInfo NextFile in TheFolder.GetFiles())
- {
- if (NextFile.Name == "0-0-11.grid")
- continue;
- // 获取文件完整路径
- string heatmappath = NextFile.FullName; }
【CefSharp】 禁用右键菜单 与 控制弹出窗口的方式(限版本39.0.0.1)
作者:admin 日期:2022-10-24
CefSharp 自定义右键菜单 (Winform版)
作者:admin 日期:2022-10-24
- /* 引用
- using CefSharp;
- using CefSharp.WinForms;
- using System;
- using System.Collections.Generic;
- */
- public class MenuHandler : IContextMenuHandler
- {
- void IContextMenuHandler.OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
- {
- //主要修改代码在此处;如果需要完完全全重新添加菜单项,首先执行model.Clear()清空菜单列表即可.
- //需要自定义菜单项的,可以在这里添加按钮;
- if (model.Count > 0)
- {
- model.AddSeparator();//添加分隔符;
- }
- model.AddItem((CefMenuCommand)26501, "Show DevTools");
- model.AddItem((CefMenuCommand)26502, "Close DevTools");
- }
- bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
- {
- //命令的执行,点击菜单做什么事写在这里.
- if (commandId == (CefMenuCommand)26501)
- {
- browser.GetHost().ShowDevTools();
- return true;
- }
- if (commandId == (CefMenuCommand)26502)
- {
- browser.GetHost().CloseDevTools();
- return true;
- }
- return false;
- }
- void IContextMenuHandler.OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
- {
- var webBrowser = (ChromiumWebBrowser)browserControl;
- Action setContextAction = delegate ()
- {
- webBrowser.ContextMenu = null;
- };
- webBrowser.Invoke(setContextAction);
- }
- bool IContextMenuHandler.RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
- {
- //return false 才可以弹出;
- return false;
- }
- //下面这个官网Example的Fun,读取已有菜单项列表时候,实现的IEnumerable,如果不需要,完全可以注释掉;不属于IContextMenuHandler接口规定的
- private static IEnumerable<Tuple<string, CefMenuCommand, bool>> GetMenuItems(IMenuModel model)
- {
- for (var i = 0; i < model.Count; i++)
- {
- var header = model.GetLabelAt(i);
- var commandId = model.GetCommandIdAt(i);
- var isEnabled = model.IsEnabledAt(i);
- yield return new Tuple<string, CefMenuCommand, bool>(header, commandId, isEnabled);
- }
- }
- }
- //在初始化ChromiumWebBrowser后,指定其MenuHandler 即可.
- browser1.MenuHandler = new MenuHandler();
关于代码,再啰嗦几点:
1.CefSharp右键菜单功能由IContextMenuHandler接口定义.
2.有的人看了官方的例子,可能会卡在webBrowser.Dispatcher.Invoke上面. winfrom中是没有Dispatcher的,Dispatcher只是调度器,在winform中直接使用Invoke调用即可,跟平时写的跨线程的UI访问需要使用委托来访问以确保线程安全一样.
3.官方的Example也是显示实现接口,文章代码尽量与翻译官方Example所以写的显示实现接口,实际上隐式实现接口是一样可用的.
C#获取当前日期时间
作者:admin 日期:2022-08-25
我们可以通过使用DataTime这个类来获取当前的时间。通过调用类中的各种方法我们可以获取不同的时间:如:日期(2008-09-04)、时间(12:12:12)、日期+时间(2008-09-04 12:11:10)等。
//获取日期+时间
DateTime.Now.ToString(); // 2008-9-4 20:02:10
DateTime.Now.ToLocalTime().ToString(); // 2008-9-4 20:12:12
//获取日期
DateTime.Now.ToLongDateString().ToString(); // 2008年9月4日
DateTime.Now.ToShortDateString().ToString(); // 2008-9-4
DateTime.Now.ToString("yyyy-MM-dd"); // 2008-09-04
DateTime.Now.Date.ToString(); // 2008-9-4 0:00:00
//获取时间
DateTime.Now.ToLongTimeString().ToString(); // 20:16:16
DateTime.Now.ToShortTimeString().ToString(); // 20:16
DateTime.Now.ToString("hh:mm:ss"); // 08:05:57
DateTime.Now.TimeOfDay.ToString(); // 20:33:50.7187500
c#中Split用法
作者:admin 日期:2009-02-05
一、引入命名空间
using System.Text.RegularExpressions;
1、用字符串分隔:
string str="aaajsbbbjsccc";
string[] sArray=Regex.Split(str,"js",RegexOptions.IgnoreCase);
foreach (string i in sArray) Response.Write(i.ToString() + "<br>");
输出结果:
aaa
bbb
ccc
2、用多个字符来分隔:
string str="aaajbbbscccjdddseee";
string[] sArray=str.Split(new char[2]{'j','s'});
foreach(string i in sArray) Response.Write(i.ToString() + "<br>");
输出结果:
aaa
bbb
ccc
ddd
eee
3、用单个字符来分隔:
string str="aaajbbbjccc";
string[] sArray=str.Split('j');
foreach(string i in sArray) Response.Write(i.ToString() + "<br>");
输出结果:
aaa
bbb
ccc
asp.net(C#)用datagrid和datalist显示数据
作者:admin 日期:2009-02-04
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=sa;database=your databease");
con.open();
string Provincesql = "Select * FROM table1";
SqlCommand comm = new SqlCommand(Provincesql, conn);
SqlDataReader dr = comm.ExecuteReader();
datagrid1.DataSource = dr;
datagrid1.DataBind();
datalist如下:
SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=sa;database=your databease");
con.open();
string Provincesql = "Select * FROM table1";
SqlDataAdapter adapter = new SqlDataAdapter(Provincesql, conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "company");
DataList1.DataSource=ds;
DataList1.DataBind();
页面部分的操作如下:
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"field(在table1中的任意字段)") %>
</ItemTemplate>
</asp:DataList>
C# 中文在URL中的编码
作者:admin 日期:2009-02-04
问题来源:
正在研究一个程序,输入一个关键字,能够把这个关键字发送到Google,yahoo等搜索引擎,进行搜索,然后打开结果网页。原理很简单。比如在Google搜索China,搜索结果页面的URL就是“http://www.google.com/search?hl=zh-CN&q=China&lr=”。只要替换红颜色的内容,就可以按照不同的关键字搜索。
但是如果关键字是中文,就会出现问题。比如在google搜索“中国”,Url是“http://www.google.com/search?hl=zh-CN&newwindow=1&q=%E4%B8%AD%E5%9B%BD&lr=”。汉字“中国”被按照UTF-8的格式进行编码。
不仅汉字进行编码,一些特殊字符也会进行编码。比如搜索“C#”,URL是“http://www.google.com/search?hl=zh-CN&newwindow=1&q=C%23&lr=”。
一般来说,国外的网站都是按照UTF-8编码,而“百度”是按照“GB2312”进行编码的。比如搜索“中国”,URL是“http://www.baidu.com/s?wd=%D6%D0%B9%FA&cl=3”
我们对比一下:C#中国的编码
编码 结果 网站
UTF-8 C%23%E4%B8%AD%E5%9B%BD Google
GB2312 C%23%D6%D0%B9%FA BaiDu
总结:
UTF-8中,一个汉字对应三个字节,GB2312中一个汉字占用两个字节。
不论何种编码,字母数字都不编码,特殊符号编码后占用一个字节。
//按照UTF-8进行编码
string tempSearchString1 = System.Web.HttpUtility.UrlEncode("C#中国");
//按照GB2312进行编码
string tempSearchString2 = System.Web.HttpUtility.UrlEncode("C#中国",System.Text.Encoding.GetEncoding("GB2312"));
c#上传文件并限制上传文件类型
作者:admin 日期:2009-01-07
下面的示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该示例只允许上载扩展名为 .doc 或 .xls 的文件。调用 Path.GetExtension 方法来返回要上载的文件的扩展名。如果文件扩展名为 .doc 或 .xls,则调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadBtn_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
string savePath = @"c:\temp\uploads";
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
// Get the name of the file to upload.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the uploaded file.
string extension = System.IO.Path.GetExtension(fileName);
// Allow only files with .doc or .xls extensions
// to be uploaded.
if ((extension == ".doc") | (extension == ".xls"))
{
// Append the name of the file to upload to the path.
savePath += fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user that their file was successfully uploaded.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user why their file was not uploaded.
UploadStatusLabel.Text = "Your file was not uploaded because " +
"it does not have a .doc or .xls extension.";
}
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadBtn"
Text="Upload file"
OnClick="UploadBtn_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
c#上传文件并限制上传文件大小
作者:admin 日期:2009-01-07
面的示例演示如何创建 FileUpload 控件,该控件将文件保存到代码中指定的路径。该控件将上载文件的大小限制为 5 MB。使用 PostedFile 属性来访问基础 ContentLength 属性并返回文件的大小。如果要上载的文件的大小小于 2 MB,则调用 SaveAs 方法将文件保存到服务器上的指定路径。除了检查应用程序代码中的最大文件大小设置之外,您还可以将 httpRuntime 元素的 maxRequestLength 属性设置为应用程序配置文件中所允许的最大大小。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadButton_Click(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
string savePath = @"c:\temp\uploads\";
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
// Get the size in bytes of the file to upload.
int fileSize = FileUpload1.PostedFile.ContentLength;
// Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
if (fileSize < 2100000)
{
// Append the name of the uploaded file to the path.
savePath += Server.HtmlEncode(FileUpload1.FileName);
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user that the file was uploaded successfully.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user why their file was not uploaded.
UploadStatusLabel.Text = "Your file was not uploaded because " +
"it exceeds the 2 MB size limit.";
}
}
else
{
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadButton"
Text="Upload file"
OnClick="UploadButton_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
c#上传文件并保存到指定目录
作者:admin 日期:2009-01-07
下面的示例演示如何创建 FileUpload 控件,该控件将文件保存到文件系统中针对应用程序的指定目录。使用 HttpRequest.PhysicalApplicationPath 属性来获取当前正在执行的服务器应用程序的根目录的物理文件系统路径。调用 SaveAs 方法将文件保存到服务器上的指定路径。
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void UploadButton_Click(object sender, EventArgs e)
{
// Save the uploaded file to an "Uploads" directory
// that already exists in the file system of the
// currently executing ASP.NET application.
// Creating an "Uploads" directory isolates uploaded
// files in a separate directory. This helps prevent
// users from overwriting existing application files by
// uploading files with names like "Web.config".
string saveDir = @"\Uploads\";
// Get the physical file system path for the currently
// executing application.
string appPath = Request.PhysicalApplicationPath;
// Before attempting to save the file, verify
// that the FileUpload control contains a file.
if (FileUpload1.HasFile)
{
string savePath = appPath + saveDir +
Server.HtmlEncode(FileUpload1.FileName);
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user that the file was uploaded successfully.
UploadStatusLabel.Text = "Your file was uploaded successfully.";
}
else
{
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
</script>
<html >
<head runat="server">
<title>FileUpload Class Example</title>
</head>
<body>
<h3>FileUpload Class Example: Save To Application Directory</h3>
<form id="form1" runat="server">
<div>
<h4>Select a file to upload:</h4>
<asp:FileUpload id="FileUpload1"
runat="server">
</asp:FileUpload>
<br/><br/>
<asp:Button id="UploadButton"
Text="Upload file"
OnClick="UploadButton_Click"
runat="server">
</asp:Button>
<hr />
<asp:Label id="UploadStatusLabel"
runat="server">
</asp:Label>
</div>
</form>
</body>
</html>
广告位