2 using System.Collections.Generic;
3 using System.ComponentModel;
19 public partial class WebView : UserControl
22 private const string RUNTIMEWEBVIEW =
"Runtime del WebView2 de Microsoft Edge";
25 #region Propiedades privadas 26 private Assembly _oAssemblyGetView2 = null;
27 private dynamic _oWebView2 = null;
28 private Type _oTypeWebView2 = null;
29 private dynamic _oWebViewController = null;
30 private Type _oTypeWebViewController = null;
31 private bool _lScriptErrorsSuppressed =
false;
32 private bool _lOpenLinkDefaultBrowser =
true;
33 private bool _lOpenNewWindowDefaultBrowser =
false;
34 private bool _lCancelNewWindowRequested =
false;
35 private bool _lContextMenuEnabled =
true;
36 private bool _lAreBrowserAcceleratorKeysEnabled =
true;
37 private bool _lResponseReceived =
false;
38 private bool _lAutoRefreshDocument =
false;
39 private string _cUserDataFolder =
string.Empty;
40 private BackgroundWorker _oBackgroundWorker = null;
41 private bool _lBackgroudWorkerIsRunning =
false;
42 private string _cPathRuntime =
"";
43 private string _cExecutableRuntime =
"";
44 private bool _lRuntimeInstalled =
false;
48 private bool _disposed =
false;
49 #endregion Propiedades privadas 51 #region Eventos y delegados 52 public event _NavigationStarting_Handler _NavigationStarting;
60 public delegate
void _NavigationStarting_Handler();
74 public delegate
void _NavigationCompleted_Handler(
string tcUrl,
bool tlIsSuccess);
84 public delegate
void _MouseUp_Handler(
string tcTipo,
string tcValue,
string tcId);
94 public delegate
void _MouseDown_Handler(
string tcTipo,
string tcValue);
104 public delegate
void _MouseLeave_Handler();
115 public delegate
void _WebResourceResponseReceived_Handler(
int tnHttpResponseStatusCode);
125 public delegate
void _KeyPress_Handler(KeyPressEventArgs e);
137 public delegate
void _Click_Handler(
object sender, EventArgs e);
148 public delegate
void _EndGetHTML_Handler(
string tcHtml);
153 public event _Log_Handler
_Log;
159 public delegate
void _Log_Handler(
string tcLog);
169 public delegate
void _PrintBefore_Handler();
179 public delegate
void _PrintAfter_Handler();
180 #endregion Evenos y delegados 202 IsRunTimeInstalled();
204 #endregion Consctructor 206 #region Propiedades públicas 207 public string _Mensaje_Error =
string.Empty;
215 public HtmlDocument Document
217 get {
return _oWebView2 != null ? _oWebView2.Document : null; }
223 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
224 public bool ScriptErrorsSuppressed
226 get {
return _lScriptErrorsSuppressed; }
229 if (_oWebView2 != null)
231 _oWebView2.ScriptErrorsSuppressed = value;
232 _lScriptErrorsSuppressed = value;
241 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
242 public bool _OpenLinkDefaultBrowser
244 get {
return _lOpenLinkDefaultBrowser; }
247 _lOpenLinkDefaultBrowser = value;
249 if (_oWebView2 != null)
250 _oWebView2._OpenLinkDefaultBrowser = value;
258 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
259 public bool _OpenNewWindowDefaultBrowser
261 get {
return _lOpenNewWindowDefaultBrowser; }
263 _lOpenNewWindowDefaultBrowser = value;
265 if (_oWebView2 != null)
266 _oWebView2._OpenNewWindowDefaultBrowser = value;
274 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
275 public bool _CancelNewWindowRequested
277 get {
return _lCancelNewWindowRequested; }
280 _lCancelNewWindowRequested = value;
282 if (_oWebView2 != null)
283 _oWebView2._CancelNewWindowRequested = value;
291 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
292 public bool _ContextMenuEnabled
294 get {
return _lContextMenuEnabled; }
297 _lContextMenuEnabled = value;
299 if (_oWebView2 != null)
300 _oWebView2._ContextMenuEnabled = value;
307 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
308 public bool _AreBrowserAcceleratorKeysEnabled
310 get {
return _lAreBrowserAcceleratorKeysEnabled; }
313 _lAreBrowserAcceleratorKeysEnabled = value;
315 if (_oWebView2 != null)
316 _oWebView2._AreBrowserAcceleratorKeysEnabled = value;
324 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
325 public bool _ResponseReceived
327 get {
return _lResponseReceived; }
329 _lResponseReceived = value;
331 if (_oWebView2 != null)
332 _oWebView2._ResponseReceived = value;
339 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
340 public bool _AutoRefreshDocument
342 get {
return _lAutoRefreshDocument; }
344 _lAutoRefreshDocument = value;
346 if (_oWebView2 != null)
347 _oWebView2._AutoRefreshDocument = value;
354 [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
355 public string _UserDataFolder
357 get {
return _cUserDataFolder; }
360 _cUserDataFolder = value;
362 if (_oWebView2 != null)
363 _oWebView2._UserDataFolder = value;
367 private Dictionary<string, string> _dicVirtualHostNameMappings =
new Dictionary<string, string>();
376 if (
string.IsNullOrWhiteSpace(alias) ||
string.IsNullOrWhiteSpace(ruta))
379 if (_dicVirtualHostNameMappings.ContainsKey(alias))
380 _dicVirtualHostNameMappings[alias] = ruta;
382 _dicVirtualHostNameMappings.Add(alias, ruta);
388 public bool _WebViewOk
390 get {
return _oWebView2 != null; }
392 #endregion Propiedades públicas 394 #region Métodos públicos 395 public void _Initialize()
400 if (_oWebView2 != null)
411 if (_oWebView2 != null)
412 _oWebView2._RefreshDocument();
421 if (_oWebView2 != null)
422 _oWebView2.DisableElementById(tcId);
432 _oWebView2?._Print(tcTitulo);
441 public dynamic
_PrintAsync(
string tcPrinterName,
int tnCopies = 0,
string tcTitulo =
"")
443 return _oWebView2?._PrintAsync(tcPrinterName, tnCopies, tcTitulo);
447 #endregion Métodos públicos 449 #region Métodos privados 450 private void GetTypeWebView(Assembly toAssembly)
458 _oTypeWebView2 = toAssembly.GetType(
"Sage.ES.S50.WebView2.WebView2");
460 if (_oWebView2 == null)
461 _oWebView2 = Activator.CreateInstance(_oTypeWebView2, null);
463 catch (Exception loEx)
465 _LogWebView($
"Se ha producido un error al instanciar el componente WebView2 {loEx.Message}");
473 private void GetTypeWebViewController(Assembly toAssembly)
477 _oTypeWebViewController = toAssembly.GetType(
"Sage.ES.S50.WebView2.WebViewController");
479 if (_oWebViewController == null)
480 _oWebViewController = Activator.CreateInstance(_oTypeWebViewController, null);
482 catch (Exception loEx)
484 _LogWebView($
"Se ha producido un error al instanciar el WebViewController {loEx.Message}");
493 private Assembly LoadAssemblyWebView()
495 if (_oAssemblyGetView2 != null)
496 return _oAssemblyGetView2;
498 Assembly loAssembly = null;
500 string lcDllWebView =
"Sage.ES.S50.WebView2.dll";
502 var assemblies = AppDomain.CurrentDomain.GetAssemblies();
503 IEnumerable<Assembly> lstAssemblies = lstAssemblies = assemblies.Where(x => x.ManifestModule.ToString() == lcDllWebView).ToList();
505 if (lstAssemblies != null && lstAssemblies.Count() == 1)
506 loAssembly = lstAssemblies.First();
509 string lcRuta = Path.GetDirectoryName(GetType().Assembly.Location);
510 string lcLibraryWebView = Path.Combine(lcRuta, lcDllWebView);
512 if (File.Exists(lcLibraryWebView))
513 loAssembly = LoadAssembly(lcLibraryWebView);
515 _LogWebView(
"No se ha encontrado la librería para la carga del navegador WebView2.");
518 _oAssemblyGetView2 = loAssembly;
528 private Assembly LoadAssembly(
string tcPathFileDll)
531 Assembly addonAssembly = null;
535 addonAssembly = Assembly.LoadFrom(tcPathFileDll);
541 if (addonAssembly != null)
545 var appDomain = AppDomain.CreateDomain(tcPathFileDll);
546 addonAssembly = appDomain.Load(File.ReadAllBytes(tcPathFileDll));
553 if (addonAssembly != null)
557 addonAssembly = Assembly.LoadFile(tcPathFileDll);
564 return addonAssembly;
573 return IsRunTimeInstalled();
580 private bool IsRunTimeInstalled()
586 LoadAssemblyWebView();
588 if (_oAssemblyGetView2 != null)
590 GetTypeWebViewController(_oAssemblyGetView2);
592 if (_oTypeWebViewController != null && _oWebViewController != null)
594 var loVersion = _oWebViewController._GetVersion();
596 llOk = (loVersion._RuntimeInstalado);
599 _LogWebView($
"No se ha podido instanciar el componente WebViewController. Revise si tiene instalado el {RUNTIMEWEBVIEW} (3).");
603 if (
string.IsNullOrWhiteSpace(_Mensaje_Error))
604 _LogWebView($
"No se ha podido instanciar el componente WebViewController. Revise si es necesario instalar el {RUNTIMEWEBVIEW} (2).");
608 _LogWebView($
"No se ha podido cargar el componente WebViewController. Revise si es necesario instalar {RUNTIMEWEBVIEW} (1).");
610 catch (Exception loEx)
612 _LogWebView($
"No se ha podido cargar el componente WebViewController. Revise si es necesario instalar {RUNTIMEWEBVIEW} (4). {loEx.Message}.");
622 private bool InstanciarWebView()
626 LoadAssemblyWebView();
628 if (_oAssemblyGetView2 != null)
630 llOk = IsRunTimeInstalled();
634 GetTypeWebView(_oAssemblyGetView2);
636 if (_oTypeWebView2 != null)
638 Controls.Add(_oWebView2);
640 _oWebView2.Dock = DockStyle.Fill;
641 _oWebView2._UserDataFolder = _cUserDataFolder;
643 foreach (KeyValuePair<string,string> mapping
in _dicVirtualHostNameMappings)
645 _oWebView2.AddVirtualHostNameMapping(mapping.Key, mapping.Value);
648 ExecuteWebViewEvents(
true);
649 llOk = ExecuteWebViewEvents();
652 _LogWebView(
"No se ha podido instanciar el componente WebView2.");
655 _LogWebView(
"No se encuentra la versión del Runtime necesaria para instanciar el componente WebView2.");
658 _LogWebView(
"No se ha podido cargar el componente WebView2.");
671 private bool EventhandlerWebView(dynamic toInstance,
bool tlUnSubscribe =
false,
string tcMetodo =
"",
string tcEvento =
"")
673 if (_oTypeWebView2 == null)
678 MethodInfo method = GetType().GetMethod(tcMetodo, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
679 EventInfo eventInfo = _oTypeWebView2.GetEvent(tcEvento);
681 if (method != null && eventInfo != null)
686 Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType,
this, method);
691 eventInfo.RemoveEventHandler(toInstance, handler);
693 eventInfo.AddEventHandler(toInstance, handler);
703 _LogWebView(
"No se ha podido subscribir al evento " + tcEvento +
" del WebView2.");
711 _LogWebView(
"No se ha podido subscribir al evento " + tcEvento +
" del WebView2.");
722 private bool ExecuteWebViewEvents(
bool tlUnSubscribe =
false)
726 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_NavigationStartingWebView",
"_NavigationStarting");
727 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_NavigationCompletedWebView",
"_NavigationCompleted");
728 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_WebResourceResponseReceivedWebView",
"_WebResourceResponseReceived");
729 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_MouseUpWebView",
"_MouseUp");
730 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_MouseDownWebView",
"_MouseDown");
731 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_MouseLeaveWebView",
"_MouseLeave");
732 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_KeyPressWebView",
"_KeyPress");
733 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_ContentClickWebView",
"_ContentClick");
734 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_EndGetHTMWebView",
"_EndGetHTML");
735 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_LogWebView",
"_Log");
736 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_PrintBeforeWebView",
"_PrintBefore");
737 llOk = EventhandlerWebView(_oWebView2, tlUnSubscribe,
"_PrintAfterWebView",
"_PrintAfter");
747 private void Visibility()
757 private void MensajeError(
string tcMensaje_Error)
759 _Mensaje_Error = tcMensaje_Error;
761 _LogWebView(tcMensaje_Error);
768 private bool InstallRuntime()
770 _LogWebView(
"Inicio de la instalación del Runtime del WebView2");
774 Process loProcess =
new Process();
776 string lcPathFileNameServer = Path.Combine(_cPathRuntime, _cExecutableRuntime);
778 if (!File.Exists(lcPathFileNameServer))
780 _LogWebView($
"No se ha encontrado en el servidor el fichero para la instalación del {RUNTIMEWEBVIEW}.");
784 string lcTempPath = Path.GetTempPath();
785 string lcPathFileNameTemp = Path.Combine(lcTempPath, _cExecutableRuntime);
787 if (File.Exists(lcPathFileNameTemp))
788 File.Delete(lcPathFileNameTemp);
790 ProcessStartInfo loExe =
new ProcessStartInfo(lcPathFileNameServer);
792 loExe.WorkingDirectory = lcTempPath;
793 loExe.Arguments =
@" /silent /install";
794 loProcess.StartInfo = loExe;
795 loProcess.StartInfo.CreateNoWindow =
true;
796 loProcess.EnableRaisingEvents =
true;
797 loExe.WindowStyle = ProcessWindowStyle.Hidden;
801 llOk = loProcess.Start();
802 loProcess.WaitForExit();
804 if (loProcess.ExitCode == 0)
805 _LogWebView($
"Ha finalizado la instalación del {RUNTIMEWEBVIEW}.");
807 _LogWebView($
"Se ha producido un error al instalar el {RUNTIMEWEBVIEW}." + Environment.NewLine +
"Instale manualmente el {RUNTIMEWEBVIEW}. En el caso de dar error la instalación manual reinicie el ordenador antes de su instalación.");
809 catch (Exception loEx)
811 _LogWebView($
"Se ha producido un error al instalar el {RUNTIMEWEBVIEW}.{Environment.NewLine}{loEx.Message }.");
821 private void DoInstallRuntime()
823 if (!_lBackgroudWorkerIsRunning)
825 _lBackgroudWorkerIsRunning =
true;
828 _oBackgroundWorker =
new BackgroundWorker();
831 _oBackgroundWorker.WorkerSupportsCancellation =
true;
832 _oBackgroundWorker.WorkerReportsProgress =
false;
835 _oBackgroundWorker.DoWork +=
new DoWorkEventHandler(ExecuteRunWorker);
836 _oBackgroundWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(RunWorkerCompleted);
839 _oBackgroundWorker.RunWorkerAsync();
848 private void ExecuteRunWorker(
object sender, DoWorkEventArgs e)
852 WebviewResultadoBackgroundWorker loResult =
new WebviewResultadoBackgroundWorker();
853 loResult._Resultado = InstallRuntime();
857 catch (Exception loEx)
859 _LogWebView($
"Se ha producido un error al instalar {RUNTIMEWEBVIEW}.{Environment.NewLine}{loEx.Message }.");
868 private void RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
870 if (e.Cancelled ==
false && e.Error == null && e.Result != null && e.Result is WebviewResultadoBackgroundWorker)
872 WebviewResultadoBackgroundWorker loWebviewResultadoBackgroundWorker = (WebviewResultadoBackgroundWorker)e.Result;
874 _lRuntimeInstalled = loWebviewResultadoBackgroundWorker._Resultado;
877 _lBackgroudWorkerIsRunning =
false;
879 #endregion Métodos privados 881 #region Métodos protected internal 882 protected internal void _NavigationStartingWebView()
887 _NavigationStarting?.Invoke();
896 _WebResourceResponseReceived?.Invoke(tnHttpResponseStatusCode);
904 protected internal void _NavigationCompletedWebView(
string tcUrl,
bool tlIsSuccess)
906 _NavigationCompleted?.Invoke(tcUrl, tlIsSuccess);
915 protected internal void _MouseUpWebView(
string tcTipo,
string tcValue,
string tcId)
917 _MouseUp?.Invoke(tcTipo, tcValue, tcId);
919 _MouseUpExecute(tcTipo, tcValue, tcId);
927 protected internal void _MouseDownWebView(
string tcTipo,
string tcValue)
929 _MouseDown?.Invoke(tcTipo, tcValue);
935 protected internal void _MouseLeaveWebView()
937 _MouseLeave?.Invoke();
944 protected internal void _LogWebView(
string tcLog)
948 _Mensaje_Error = tcLog;
950 _Log_Analisis(tcLog);
959 protected internal void _KeyPressWebView(KeyPressEventArgs e)
961 _KeyPress?.Invoke(e);
969 protected internal void _ContentClickWebView(
object sender, EventArgs e)
971 _ContentClick?.Invoke(sender, e);
977 protected internal void _EndGetHTMWebView(
string tcHtml)
979 _EndGetHTML?.Invoke(tcHtml);
985 protected internal void _PrintBeforeWebView()
987 _PrintBefore?.Invoke();
993 protected internal void _PrintAfterWebView()
995 _PrintAfter?.Invoke();
999 #endregion Métodos protected internal 1001 #region Métodos protected 1002 protected void _GetHtml()
1011 if (_oWebView2 != null)
1012 _oWebView2._GetHtml();
1021 if (_oWebView2 != null)
1022 _oWebView2._ReadOnlyEditor(tlReadOnly);
1030 if (_oWebView2 != null)
1031 _oWebView2._FocusEditor();
1040 if (_oWebView2 != null)
1041 _oWebView2._PutDataEditor(tcData);
1043 #endregion Métodos protected 1045 #region Métodos public 1046 public void _InstallRuntime(
string tcPath,
string tcExecutable =
"MicrosoftEdgeWebview2Setup.exe")
1054 _LogWebView($
"Se va a realizar la instalación del {RUNTIMEWEBVIEW}. (_InstallRuntime)");
1056 _cPathRuntime = tcPath;
1057 _cExecutableRuntime = tcExecutable;
1059 if (File.Exists(Path.Combine(_cPathRuntime, _cExecutableRuntime)))
1061 _LogWebView($
"Se va a realizara la instalación del {RUNTIMEWEBVIEW}. {_cPathRuntime}. (_InstallRuntime)");
1066 _LogWebView($
"No existe el fichero de instalación del {RUNTIMEWEBVIEW} ({_cExecutableRuntime}) en la ruta {_cPathRuntime}.");
1075 if (_oWebView2 != null)
1076 _oWebView2.Navigate(tcUrl);
1080 _LogWebView($
"Se ha producido un error al navegar a la URL {tcUrl}.");
1091 if (_oWebView2 != null)
1092 _oWebView2.NavigateToEditor(tcUrl, tcDataEditor);
1096 _LogWebView($
"Se ha producido un error al navegar al a URL {tcUrl}. (NavigateEditor)");
1106 if (_oWebView2 != null)
1107 _oWebView2.Navigate(toUri);
1111 _LogWebView($
"Se ha producido un error al navegar a la URL {toUri.AbsoluteUri}. ");
1122 if (_oWebView2 != null)
1123 _oWebView2.NavigateToString(tcHtmlContent);
1127 _LogWebView(
"Se ha producido un error al cargar el HTML.");
1138 public void NavigateWithPost(
string tcUrl, Stream toPostData,
string tcHeaders =
"Content-Type: application/x-www-form-urlencoded")
1140 if (_oWebView2 != null)
1141 _oWebView2.NavigateWithPost(tcUrl, toPostData, tcHeaders);
1145 _LogWebView($
"Se ha producido un error al cargar la URL {tcUrl} por POST.");
1149 #endregion Métodos public 1151 #region Métodos protected virtual 1152 protected virtual void _Inicializar()
1158 #endregion Métodos protected virtual 1160 #region Métodos public virtual 1161 public virtual void _Log_Analisis(
string tcLog)
1180 #endregion Métodos public virtual 1182 #region Estructura de resultados del BackGroundWorker 1183 public struct WebviewResultadoBackgroundWorker
1194 #endregion Estructura de resultados del BackGroundWorker _EndGetHTML_Handler _EndGetHTML
Finalización de la obtención del HTML del CKEDITOR
void NavigateWithPost(string tcUrl, Stream toPostData, string tcHeaders="Content-Type: application/x-www-form-urlencoded")
Navigación POST
void DisableElementById(string tcId)
Método para desactivar un HtmlElement
void Navigate(Uri toUri)
Navega a la URL del URI pasado por parámetro
_PrintBefore_Handler _PrintBefore
Evento al inició del métode _Print()
void _FocusEditor()
Pasa el foco a la area de edición del CKEditor
void _Print(string tcTitulo="")
Imprime el contenido del navegador
_MouseDown_Handler _MouseDown
Gestión de la pulsación sobre los htmlements de la página
_NavigationCompleted_Handler _NavigationCompleted
Evento para capturar la finalización de la carga NavigationCompleted is raised when the WebView has c...
virtual void _WebResourceResponseReceivedWebView(int tnHttpResponseStatusCode)
Método para poder capturar las respuestas
WebView(bool tlValidateRuntime)
Constructor que valida si está instalado el Runtime del WebView
_MouseUp_Handler _MouseUp
Gestión de la pulsación sobre los htmlements de la página
_KeyPress_Handler _KeyPress
Gestión de la pulsación de una tacla sobre la página
void NavigateToString(string tcHtmlContent)
Navegación mediante el método NavigateToString
void _RefreshDocument()
Método para refrescar la instancia "Document" -> "HtmlDocument"
_WebResourceResponseReceived_Handler _WebResourceResponseReceived
Evento de respuesta de recurso web recibido
_Click_Handler _ContentClick
Evento de click en el contenido
void _ReadOnlyEditor(bool tlReadOnly)
Establece el valor de ReadOnly del CKEditor
void Navigate(string tcUrl)
Navega a la URL del URI pasado por parámetro
_PrintAfter_Handler _PrintAfter
Evento al final del métode _Print()
bool _Resultado
Resultado de la instalación en el BackGroundWorker
void _PutDataEditor(string tcData)
Añade un texto en una posición actual del curso dentro del CkEditor
_Log_Handler _Log
Gestión del Log
void NavigateToEditor(string tcUrl, string tcDataEditor)
Navegar a la URL mediante el método Navigate
virtual bool _MouseUpExecute(string tcTipo, string tcValue, string tcIdOrName)
Método para gestionar el MouseUp
_MouseLeave_Handler _MouseLeave
Gestión para el mouseLeave el WebView2
bool _IsRunTimeInstalled()
Devuelve si está instalado el Runtime del WebView
dynamic _PrintAsync(string tcPrinterName, int tnCopies=0, string tcTitulo="")
Imprime el contenido del navegador
void AddVirtualHostNameMapping(string alias, string ruta)
Método para establecer valores para crear alias de mapeo de rutas locales