因為最近項目中要嵌入幾個合作方的web頁面,原先是准備使用miniblink(一個國內大神的開源項目)的.NET封裝的,不過試用后界面渲染效果一般並且封裝是以UI顯示為目的的,如果你點擊了網頁中某個a標簽它不能開新窗口顯示,而是直接跳轉,這個需求差異需要自己完成,使用不變,故選擇CefSharp來做。
使用CefSharp的過程簡單而順利,直接新建項目並nuget引用即可,GitHub上的wiki里還有中文說明,在將它集成到項目中時候發現每次加載web頁面時從ChromiumWebBrowser控件開始顯示到DOM加載完畢這段時間內控件的背景色是白色的,但我界面風格是深色的顯得很突兀,於是走了一波谷歌到處查找解決辦法,大部分結果是說直接在Cef初始化時候添加背景色,代碼如下:
1 private static void InitializeCefSharp() 2 { 3 var settings = new CefSettings(); 4 settings.Locale = "zh-CN"; 5 //日志等級 6 settings.LogSeverity = LogSeverity.Warning; 7 settings.LogFile = "Logs"; 8 9 settings.BackgroundColor = ((uint)255 << 24) | ((uint)22 << 16) | ((uint)28 << 8) | ((uint)43 << 0);// Color.FromRgb(22, 28, 43); ;//0xFF161C2B; 10 settings.WindowlessRenderingEnabled = true; 11 //settings.CefCommandLineArgs.Add("background-color = red"); 12 13 // Set BrowserSubProcessPath based on app bitness at runtime 14 settings.BrowserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, 15 Environment.Is64BitProcess ? "x64" : "x86", 16 "CefSharp.BrowserSubprocess.exe"); 17 18 // Make sure you set performDependencyCheck false 19 Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null); 20 }
但是測試過程中發現無論設置BackgroundColor還是用CefCommandLineArgs.Add("background-color = red")來做都是不行的,依舊是有個白色背景過渡,抓狂...
后來無意中翻到StackOverFlow上有人談論過這個情況,回答問題者用此辦法可實現,於是我照着在使用了ChromiumWebBrowser的View的Code-Behind構造函數中加了如下代碼:
public DeputyPositionView() { InitializeComponent(); var browserSettings = new CefSharp.BrowserSettings(); browserSettings.BackgroundColor = 0xFF161C2B; webView1.BrowserSettings = browserSettings; }
再將項目跑起來白色背景果然不出現了,取而代之的顏色是我這里設置的0xFF161C2B。
按照常理來說初始化時候解決不了的問題那肯定會想到到控件自己的屬性里去想辦法解決,之所以這個問題浪費了我上午大部分時光就是因為CefSharp自己的api文檔里對這個BackgroundColor屬性的說明有問題(至少我表面操作是這樣的,具體我沒有去深究),我原地打轉各種值和屬性變換着試折騰好久,現貼上這段說明(原文連接):
Opaque background color used for the browser before a document is loaded and when no document color is specified. By default the background color will be the same as CefSettings.background_color. Only the RGB compontents of the specified value will be used. The alpha component must greater than 0 to enable use of the background color but will be otherwise ignored.
其中說這個IBrowserSettings接口中BackgroundColor Property默認和CefSettings的background_color是一樣的,而我前面InitializeCefSharp函數里的settings.BackgroundColor就是它!這個接口說明明顯與我實際操作結果不一樣,這個情況不知道是否有讀者遇到過,如果是我使用不當導致這個情況請在留言區告訴我。