CefSharp项目开发经验小结
CefSharp 开发经验汇总
做过2个项目,使用CefSharp.Wpf。
引用CefSharp.Wpf
操作步骤
- Nuget里面引用CefSharp.Wpf;
- 解决方案平台换成x64,编译项目;
初始化
private ChromiumWebBrowser browser1;
browser1 = new ChromiumWebBrowser();
browser1.Address = “你的网址”;
备注:若网站使用的flash制作,需要到官方下载flashplayer先安装。
一些使用技巧
截图功能:
public static BitmapImage GetScreenSnapshot(FrameworkElement ui)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
RenderTargetBitmap bmp = new RenderTargetBitmap((int)ui.ActualWidth, (int)ui.ActualHeight, 96d, 96d, PixelFormats.Pbgra32);
bmp.Render(ui);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(ms);
ms.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
bitmapImage.Freeze();
return bitmapImage;
}
}
catch
{
return null;
}
}
模拟鼠标点击和键盘输入(整站都采用flash版):
private void Login(string userName, string password)
{
Task.Run(async delegate
{
IBrowserHost host = this.browser1.GetBrowserHost();
//用户
host.SendMouseClickEvent(442, 447, MouseButtonType.Left, false, 1, CefEventFlags.None);//按下鼠标左键
await Task.Delay(100);
host.SendMouseClickEvent(442, 447, MouseButtonType.Left, true, 1, CefEventFlags.None); //松开下鼠标左键
await Task.Delay(3000);
host.ImeCommitText(userName, null, 0);
await Task.Delay(1000);
//密码
host.SendMouseClickEvent(442, 493, MouseButtonType.Left, false, 1, CefEventFlags.None);//按下鼠标左键
await Task.Delay(100);
host.SendMouseClickEvent(442, 493, MouseButtonType.Left, true, 1, CefEventFlags.None); //松开下鼠标左键
await Task.Delay(3000);
host.ImeCommitText(password, null, 0);
await Task.Delay(3000);
//登录
host.SendMouseClickEvent(471, 548, MouseButtonType.Left, false, 1, CefEventFlags.None);//按下鼠标左键
await Task.Delay(100);
host.SendMouseClickEvent(471, 548, MouseButtonType.Left, true, 1, CefEventFlags.None); //松开下鼠标左键
await Task.Delay(3000);//延迟3秒执行
//重载浏览器(失败或掉线重启)
//this.browser1.Reload();
});
}
备注:加入延迟以防操作过快而失败,html5版本直接使用js脚本即可。
来源:CSDN
作者:从来不喝咖啡
链接:https://blog.csdn.net/pxxcsdn/article/details/103890235