C# 프로그램에 크롬 브라우저 내장하기
필요 패키지
HtmlAgilityPack : HTML 파서
HtmlAgilityPack.CssSelectors : CSS 셀렉터 사용 가능
CsQuery : jQuery 기능 구현
System.Net.Http
CefSharp.WinForms : Chromium-based browser component
//-------------------------------------------------
CefSharp 사용법
크롬(Chromium ) 사용
//-----------
* 초기화
public ChromiumWebBrowser browser;
public void InitBrowser()
{
Cef.Initialize(new CefSettings());
browser = new ChromiumWebBrowser("about:blank");
pictureBox1.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
}
//-----------
* url 이동
browser.Load("www.google.com");
//-----------
* html 소스 읽기
browser.FrameLoadEnd += WebBrowserFrameLoadEnded;
private void WebBrowserFrameLoadEnded(object sender, FrameLoadEndEventArgs e)
{
if (e.Frame.IsMain)
{
//browser.ViewSource();//소스를 편집기로 띄움
browser.GetSourceAsync().ContinueWith(taskHtml =>
{
var html = taskHtml.Result;
_log("html", html);
selectNode(html, "input[name=q]");
});
}
}
//---------------------
* html 소스 파싱
- HtmlAgilityPack , HtmlAgilityPack.CssSelectors 이용
public HtmlNode selectNode(string sHtml, string sSel)
{
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(sHtml);
var document = doc.DocumentNode;
HtmlNode node = doc.QuerySelector(sSel);
_log("node", node!=null?node.OuterHtml:"");
return node;
}
//---------------------
cefsharp Tutorials
https://github.com/cefsharptutorials/cefsharptutorials/tree/master/CefSharpTutorials
https://www.youtube.com/watch?v=gphqZTCWoZE&list=PLtnonz7r7xrqI7OS0eWwc4lrwV5zqI4r3
//-----------------------------------------------
BackForwardNavigation 앞 뒤 이동
if (Browser.CanGoBack) { Browser.Back(); }
if (Browser.CanGoForward) { Browser.Forward(); }
//-----------------------------------------------
ContextMenus : ContextMenus 추가
//-----------------------------------------------
GettingSettingHtmlContent : HTML 소스 얻기, 설정
private void BrowserView_OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
Dispatcher.BeginInvoke((Action) (async () =>
{
HtmlTextBox.Text = await BrowserView.GetSourceAsync();
}));
}
private void SetHtmlButton_OnClick(object sender, RoutedEventArgs e)
{
BrowserView.LoadHtml("123");// HtmlTextBox.Text);
}
//-----------------------------------------------
InjectDotNetToJavaScript :
RegisterJsObject() 메소드가 삭제됨(사용 불가)
//-----------------------------------------------
RemoteDebugging : 디버깅 창 띄우기
public void InitBrowser4Debug()
{
//InitializeComponent();
CefSettings settings = new CefSettings() { RemoteDebuggingPort = 8088 };
Cef.Initialize(settings);
browser = new ChromiumWebBrowser("about:blank");
pictureBox1.Controls.Add(browser);
//leftBrowser.SetValue(Grid.ColumnProperty, 0);
bwDebug = new ChromiumWebBrowser("about:blank");
pictureBox2.Controls.Add(bwDebug);
//rightBrowser.SetValue(Grid.ColumnProperty, 1);
browser.FrameLoadEnd += LeftBrowser_FrameLoadEnd;
//browser.Address = "github.com";
browser.Load("www.google.com");
}
private void LeftBrowser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() =>
{
//bwDebug.Address = "localhost:8088";
bwDebug.Load("localhost:8088");
}));
}
//
Css3Basics 기본 로딩
ExecutingJavaScript 자바스크립트 실행
//-------------------------------
//자바스크립트 실행
https://github.com/cefsharptutorials/cefsharptutorials/blob/master/CefSharpTutorials/ExecutingJavaScript/MainWindow.xaml.cs
private async void excuteJS(string str)
{
if (browser.CanExecuteJavascriptInMainFrame && !string.IsNullOrWhiteSpace(str))
{
JavascriptResponse response = await browser.EvaluateScriptAsync(str);
_log(1, response.Result);
if (response.Result != null)
{
_log(2, response.Result.ToString(), "JavaScript Result");
}
}
}
//--------------------------------------------------
// 참고만
* WebBrowser 콘트롤 사용법
- IE 사용
//WebBrowser Class , IE(Internet Explorer)
//https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.webbrowser?view=netframework-4.8
// Navigates to the given URL if it is valid.
private void Navigate(String address)
{
if (String.IsNullOrEmpty(address)) return;
if (address.Equals("about:blank")) return;
if (!address.StartsWith("http://") &&
!address.StartsWith("https://"))
{
address = "http://" + address;
}
try
{
webBrowser1.Navigate(new Uri(address));
}
catch (System.UriFormatException)
{
return;
}
}
// Updates the URL in TextBoxAddress upon navigation.
private void webBrowser1_Navigated(object sender,
WebBrowserNavigatedEventArgs e)
{
_log(webBrowser1.Url.ToString());
}
//-------------------------------------------------
'Code > C#' 카테고리의 다른 글
[C#] C#에서 PHP 함수 코드 사용하기 (0) | 2020.05.04 |
---|---|
[C#] System.Management.ManagementException: Access denied 에러 해결 방법 (0) | 2020.02.10 |
[C#] 에러 해결 An object reference is required for the non-static field, method, or property Dispatcher.BeginInvoke (0) | 2020.02.01 |
C# Tips (0) | 2017.11.02 |
C# 과 Java 성능 비교 (0) | 2016.07.05 |