我有兩個webview分別為webview21、webview21,要在兩個讀完之後(NavigationCompleted),統一傳到FinishLoad,並在FinishLoad裡面將webview回去google首頁,請問有辦法達成這個嗎?不想再兩個裡面打上重複的指令
(剛接觸C#新手)
private async void webView21_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
{
FinishLoad("webView21");
}
private async void webView22_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
{
FinishLoad("webView22");
}
private async void FinishLoad(string webViewName){
MessageBox.Show(webViewName+"跑完了");
await webViewName.EnsureCoreWebView2Async();
//webViewName變成webView21或是webView22
webViewName.CoreWebView2.Navigate("https://www.google.com.tw");
}
自問自答
private async void FinishLoad(object sender){
//MessageBox.Show(webViewName+"跑完了");
WebView2 webview = (WebView2)sender;
await webview.EnsureCoreWebView2Async();
webview.CoreWebView2.Navigate("http://tw.yahoo.com");
await webview.EnsureCoreWebView2Async();
}
另一個方法
Control[] contorl = this.Controls.Find("webView21",true);
WebView2 webview = (WebView2)contorl[0];
WebViewSetting(webview)
直接將這個送去到另一個function中處理
private async void WebViewSetting(WebView2 sender)
{
WebView2 webView = (WebView2)sender;
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.Settings.AreDevToolsEnabled = false;
return;
}
您可以使用 dynamic 關鍵字和 Reflection 來達成這個目的。請看下面的程式碼範例:
// 以動態方式取得控制項
string controlName = "webView21";
dynamic control = this.Controls.Find(controlName, true)[0];
// 呼叫方法
MethodInfo method = this.GetType().GetMethod("WebViewSetting");
method.Invoke(this, new object[] { control });