This is an old revision of the document!
using System; using System.Threading.Tasks; using System.Windows.Forms; using CefSharp; using CefSharp.WinForms; public class MyForm : Form { private ChromiumWebBrowser browser; public MyForm() { InitializeComponent(); InitializeBrowser(); } private void InitializeComponent() { this.Text = "CefSharp Screenshot Example"; this.Width = 800; this.Height = 600; } private void InitializeBrowser() { var settings = new CefSettings(); Cef.Initialize(settings); browser = new ChromiumWebBrowser("https://example.com") { Dock = DockStyle.Fill }; this.Controls.Add(browser); } private async Task TakeScreenshotAsync() { // 獲取頁面高度 var pageHeight = await browser.EvaluateScriptAsync("document.body.scrollHeight"); if (pageHeight.Success) { var height = (int)(long)pageHeight.Result; // 設置模擬裝置解析度 await browser.GetDevToolsClient().Emulation.SetDeviceMetricsOverrideAsync(800, height, 1.0, true); // 截圖 var screenshot = await browser.ScreenshotAsync(); // 保存截圖 screenshot.Save("screenshot.png"); // 清除設備度量 await browser.GetDevToolsClient().Emulation.ClearDeviceMetricsOverrideAsync(); } } protected override async void OnLoad(EventArgs e) { base.OnLoad(e); await Task.Delay(2000); // 等待頁面加載完成 await TakeScreenshotAsync(); } protected override void OnFormClosing(FormClosingEventArgs e) { Cef.Shutdown(); base.OnFormClosing(e); } [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new MyForm()); } }