WebView.cs
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Drawing;
5 using System.Data;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Reflection;
10 using System.IO;
11 using System.Diagnostics;
12 using Sage.ES.S50.WebView;
13 
14 namespace Sage.ES.S50.WebView
15 {
19  public partial class WebView : UserControl
20  {
21  #region Constantes
22  private const string RUNTIMEWEBVIEW = "Runtime del WebView2 de Microsoft Edge";
23  #endregion Constantes
24 
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
50 
51  #region Eventos y delegados
52  public event _NavigationStarting_Handler _NavigationStarting;
56 
60  public delegate void _NavigationStarting_Handler();
61 
66  public event _NavigationCompleted_Handler _NavigationCompleted;
67 
68 
74  public delegate void _NavigationCompleted_Handler(string tcUrl, bool tlIsSuccess);
75 
79  public event _MouseUp_Handler _MouseUp;
80 
84  public delegate void _MouseUp_Handler(string tcTipo, string tcValue, string tcId);
85 
89  public event _MouseDown_Handler _MouseDown;
90 
94  public delegate void _MouseDown_Handler(string tcTipo, string tcValue);
95 
99  public event _MouseLeave_Handler _MouseLeave;
100 
104  public delegate void _MouseLeave_Handler();
105 
109  public event _WebResourceResponseReceived_Handler _WebResourceResponseReceived;
110 
115  public delegate void _WebResourceResponseReceived_Handler(int tnHttpResponseStatusCode);
116 
120  public event _KeyPress_Handler _KeyPress;
121 
125  public delegate void _KeyPress_Handler(KeyPressEventArgs e);
126 
130  public event _Click_Handler _ContentClick;
131 
137  public delegate void _Click_Handler(object sender, EventArgs e);
138 
142  public event _EndGetHTML_Handler _EndGetHTML;
143 
148  public delegate void _EndGetHTML_Handler(string tcHtml);
149 
153  public event _Log_Handler _Log;
154 
159  public delegate void _Log_Handler(string tcLog);
160 
164  public event _PrintBefore_Handler _PrintBefore;
165 
169  public delegate void _PrintBefore_Handler();
170 
174  public event _PrintAfter_Handler _PrintAfter;
175 
179  public delegate void _PrintAfter_Handler();
180  #endregion Evenos y delegados
181 
182  #region Constructor
183  public WebView()
187  {
188  _Inicializar();
189 
190  if (!DesignMode)
191  InstanciarWebView();
192  }
193 
198  public WebView(bool tlValidateRuntime)
199  {
200  _Inicializar();
201 
202  IsRunTimeInstalled();
203  }
204  #endregion Consctructor
205 
206  #region Propiedades públicas
207  public string _Mensaje_Error = string.Empty;
211 
215  public HtmlDocument Document
216  {
217  get { return _oWebView2 != null ? _oWebView2.Document : null; }
218  }
219 
223  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
224  public bool ScriptErrorsSuppressed
225  {
226  get { return _lScriptErrorsSuppressed; }
227  set
228  {
229  if (_oWebView2 != null)
230  {
231  _oWebView2.ScriptErrorsSuppressed = value;
232  _lScriptErrorsSuppressed = value;
233  }
234  }
235  }
236 
241  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
242  public bool _OpenLinkDefaultBrowser
243  {
244  get { return _lOpenLinkDefaultBrowser; }
245  set
246  {
247  _lOpenLinkDefaultBrowser = value;
248 
249  if (_oWebView2 != null)
250  _oWebView2._OpenLinkDefaultBrowser = value;
251  }
252  }
253 
254 
258  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
259  public bool _OpenNewWindowDefaultBrowser
260  {
261  get { return _lOpenNewWindowDefaultBrowser; }
262  set {
263  _lOpenNewWindowDefaultBrowser = value;
264 
265  if (_oWebView2 != null)
266  _oWebView2._OpenNewWindowDefaultBrowser = value;
267  }
268  }
269 
270 
274  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
275  public bool _CancelNewWindowRequested
276  {
277  get { return _lCancelNewWindowRequested; }
278  set
279  {
280  _lCancelNewWindowRequested = value;
281 
282  if (_oWebView2 != null)
283  _oWebView2._CancelNewWindowRequested = value;
284  }
285  }
286 
291  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
292  public bool _ContextMenuEnabled
293  {
294  get { return _lContextMenuEnabled; }
295  set
296  {
297  _lContextMenuEnabled = value;
298 
299  if (_oWebView2 != null)
300  _oWebView2._ContextMenuEnabled = value;
301  }
302  }
303 
307  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
308  public bool _AreBrowserAcceleratorKeysEnabled
309  {
310  get { return _lAreBrowserAcceleratorKeysEnabled; }
311  set
312  {
313  _lAreBrowserAcceleratorKeysEnabled = value;
314 
315  if (_oWebView2 != null)
316  _oWebView2._AreBrowserAcceleratorKeysEnabled = value;
317  }
318  }
319 
324  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
325  public bool _ResponseReceived
326  {
327  get { return _lResponseReceived; }
328  set {
329  _lResponseReceived = value;
330 
331  if (_oWebView2 != null)
332  _oWebView2._ResponseReceived = value;
333  }
334  }
335 
339  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
340  public bool _AutoRefreshDocument
341  {
342  get { return _lAutoRefreshDocument; }
343  set {
344  _lAutoRefreshDocument = value;
345 
346  if (_oWebView2 != null)
347  _oWebView2._AutoRefreshDocument = value;
348  }
349  }
350 
354  [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
355  public string _UserDataFolder
356  {
357  get { return _cUserDataFolder; }
358  set
359  {
360  _cUserDataFolder = value;
361 
362  if (_oWebView2 != null)
363  _oWebView2._UserDataFolder = value;
364  }
365  }
366 
367  private Dictionary<string, string> _dicVirtualHostNameMappings = new Dictionary<string, string>();
368 
374  public void AddVirtualHostNameMapping(string alias, string ruta)
375  {
376  if (string.IsNullOrWhiteSpace(alias) || string.IsNullOrWhiteSpace(ruta))
377  return;
378 
379  if (_dicVirtualHostNameMappings.ContainsKey(alias))
380  _dicVirtualHostNameMappings[alias] = ruta;
381  else
382  _dicVirtualHostNameMappings.Add(alias, ruta);
383  }
384 
388  public bool _WebViewOk
389  {
390  get { return _oWebView2 != null; }
391  }
392  #endregion Propiedades públicas
393 
394  #region Métodos públicos
395  public void _Initialize()
399  {
400  if (_oWebView2 != null)
401  return;
402 
403  InstanciarWebView();
404  }
405 
409  public void _RefreshDocument()
410  {
411  if (_oWebView2 != null)
412  _oWebView2._RefreshDocument();
413  }
414 
419  public void DisableElementById(string tcId)
420  {
421  if (_oWebView2 != null)
422  _oWebView2.DisableElementById(tcId);
423  }
424 
425 
430  public void _Print(string tcTitulo = "")
431  {
432  _oWebView2?._Print(tcTitulo);
433  }
434 
441  public dynamic _PrintAsync(string tcPrinterName, int tnCopies = 0, string tcTitulo = "")
442  {
443  return _oWebView2?._PrintAsync(tcPrinterName, tnCopies, tcTitulo);
444  }
445 
446 
447  #endregion Métodos públicos
448 
449  #region Métodos privados
450  private void GetTypeWebView(Assembly toAssembly)
455  {
456  try
457  {
458  _oTypeWebView2 = toAssembly.GetType("Sage.ES.S50.WebView2.WebView2");
459 
460  if (_oWebView2 == null)
461  _oWebView2 = Activator.CreateInstance(_oTypeWebView2, null);
462  }
463  catch (Exception loEx)
464  {
465  _LogWebView($"Se ha producido un error al instanciar el componente WebView2 {loEx.Message}");
466  }
467  }
468 
473  private void GetTypeWebViewController(Assembly toAssembly)
474  {
475  try
476  {
477  _oTypeWebViewController = toAssembly.GetType("Sage.ES.S50.WebView2.WebViewController");
478 
479  if (_oWebViewController == null)
480  _oWebViewController = Activator.CreateInstance(_oTypeWebViewController, null);
481  }
482  catch (Exception loEx)
483  {
484  _LogWebView($"Se ha producido un error al instanciar el WebViewController {loEx.Message}");
485  }
486  }
487 
488 
493  private Assembly LoadAssemblyWebView()
494  {
495  if (_oAssemblyGetView2 != null)
496  return _oAssemblyGetView2;
497 
498  Assembly loAssembly = null;
499 
500  string lcDllWebView = "Sage.ES.S50.WebView2.dll";
501 
502  var assemblies = AppDomain.CurrentDomain.GetAssemblies();
503  IEnumerable<Assembly> lstAssemblies = lstAssemblies = assemblies.Where(x => x.ManifestModule.ToString() == lcDllWebView).ToList();
504 
505  if (lstAssemblies != null && lstAssemblies.Count() == 1)
506  loAssembly = lstAssemblies.First();
507  else
508  {
509  string lcRuta = Path.GetDirectoryName(GetType().Assembly.Location); // Buscamos la ruta don de tenemos la dll de Modelos "sage.50.exe"
510  string lcLibraryWebView = Path.Combine(lcRuta, lcDllWebView);
511 
512  if (File.Exists(lcLibraryWebView))
513  loAssembly = LoadAssembly(lcLibraryWebView);
514  else
515  _LogWebView("No se ha encontrado la librería para la carga del navegador WebView2.");
516  }
517 
518  _oAssemblyGetView2 = loAssembly;
519 
520  return loAssembly;
521  }
522 
528  private Assembly LoadAssembly(string tcPathFileDll)
529  {
530  // Intentar cargar el ensamblado de las 3 formas que nos funcionan.
531  Assembly addonAssembly = null;
532 
533  try
534  {
535  addonAssembly = Assembly.LoadFrom(tcPathFileDll);
536  }
537  catch (Exception)
538  {
539  }
540 
541  if (addonAssembly != null)
542  {
543  try
544  {
545  var appDomain = AppDomain.CreateDomain(tcPathFileDll);
546  addonAssembly = appDomain.Load(File.ReadAllBytes(tcPathFileDll));
547  }
548  catch (Exception)
549  {
550  }
551  }
552 
553  if (addonAssembly != null)
554  {
555  try
556  {
557  addonAssembly = Assembly.LoadFile(tcPathFileDll);
558  }
559  catch (Exception)
560  {
561  }
562  }
563 
564  return addonAssembly;
565  }
566 
571  public bool _IsRunTimeInstalled()
572  {
573  return IsRunTimeInstalled();
574  }
575 
580  private bool IsRunTimeInstalled()
581  {
582  bool llOk = false;
583 
584  try
585  {
586  LoadAssemblyWebView();
587 
588  if (_oAssemblyGetView2 != null)
589  {
590  GetTypeWebViewController(_oAssemblyGetView2);
591 
592  if (_oTypeWebViewController != null && _oWebViewController != null)
593  {
594  var loVersion = _oWebViewController._GetVersion();
595 
596  llOk = (loVersion._RuntimeInstalado);
597 
598  if (!llOk)
599  _LogWebView($"No se ha podido instanciar el componente WebViewController. Revise si tiene instalado el {RUNTIMEWEBVIEW} (3).");
600  }
601  else
602  {
603  if (string.IsNullOrWhiteSpace(_Mensaje_Error))
604  _LogWebView($"No se ha podido instanciar el componente WebViewController. Revise si es necesario instalar el {RUNTIMEWEBVIEW} (2).");
605  }
606  }
607  else
608  _LogWebView($"No se ha podido cargar el componente WebViewController. Revise si es necesario instalar {RUNTIMEWEBVIEW} (1).");
609  }
610  catch (Exception loEx)
611  {
612  _LogWebView($"No se ha podido cargar el componente WebViewController. Revise si es necesario instalar {RUNTIMEWEBVIEW} (4). {loEx.Message}.");
613  }
614 
615  return llOk;
616  }
617 
622  private bool InstanciarWebView()
623  {
624  bool llOk = false;
625 
626  LoadAssemblyWebView();
627 
628  if (_oAssemblyGetView2 != null)
629  {
630  llOk = IsRunTimeInstalled();
631 
632  if (llOk)
633  {
634  GetTypeWebView(_oAssemblyGetView2);
635 
636  if (_oTypeWebView2 != null)
637  {
638  Controls.Add(_oWebView2);
639 
640  _oWebView2.Dock = DockStyle.Fill;
641  _oWebView2._UserDataFolder = _cUserDataFolder;
642 
643  foreach (KeyValuePair<string,string> mapping in _dicVirtualHostNameMappings)
644  {
645  _oWebView2.AddVirtualHostNameMapping(mapping.Key, mapping.Value);
646  }
647 
648  ExecuteWebViewEvents(true); // Nos desubscribimos de todos los eventos
649  llOk = ExecuteWebViewEvents();
650  }
651  else
652  _LogWebView("No se ha podido instanciar el componente WebView2.");
653  }
654  else
655  _LogWebView("No se encuentra la versión del Runtime necesaria para instanciar el componente WebView2.");
656  }
657  else
658  _LogWebView("No se ha podido cargar el componente WebView2.");
659 
660  return llOk;
661  }
662 
671  private bool EventhandlerWebView(dynamic toInstance, bool tlUnSubscribe = false, string tcMetodo = "", string tcEvento = "")
672  {
673  if (_oTypeWebView2 == null)
674  return false;
675 
676  bool llOk = false;
677 
678  MethodInfo method = GetType().GetMethod(tcMetodo, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // Nos subscribiremos al método privado de la clase WebView
679  EventInfo eventInfo = _oTypeWebView2.GetEvent(tcEvento); // Evento de la clase WebView2
680 
681  if (method != null && eventInfo != null)
682  {
683  try
684  {
685  // Creamos el delegado se corresponde a `new EventHandler()
686  Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, method);
687 
688  if (handler != null) // Asignamos el eventhandler. Se corresponde a `control._URLModelo += ...`.
689  {
690  if (tlUnSubscribe)
691  eventInfo.RemoveEventHandler(toInstance, handler);
692  else
693  eventInfo.AddEventHandler(toInstance, handler);
694 
695  llOk = true;
696  }
697  }
698  catch (Exception)
699  {
700  llOk = false;
701 
702  if (!tlUnSubscribe) // De momento únicamente me interesa al subcribir
703  _LogWebView("No se ha podido subscribir al evento " + tcEvento + " del WebView2.");
704  }
705  }
706  else
707  {
708  llOk = false;
709 
710  if (!tlUnSubscribe) // De momento únicamente me interesa al subcribir
711  _LogWebView("No se ha podido subscribir al evento " + tcEvento + " del WebView2.");
712  }
713 
714  return llOk;
715  }
716 
722  private bool ExecuteWebViewEvents(bool tlUnSubscribe = false)
723  {
724  bool llOk = false;
725 
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");
738 
739 
740  return llOk;
741  }
742 
747  private void Visibility()
748  {
749  if (!Visible)
750  Visible = true;
751  }
752 
757  private void MensajeError(string tcMensaje_Error)
758  {
759  _Mensaje_Error = tcMensaje_Error;
760 
761  _LogWebView(tcMensaje_Error);
762  }
763 
768  private bool InstallRuntime()
769  {
770  _LogWebView("Inicio de la instalación del Runtime del WebView2");
771 
772  bool llOk = false;
773 
774  Process loProcess = new Process();
775 
776  string lcPathFileNameServer = Path.Combine(_cPathRuntime, _cExecutableRuntime);
777 
778  if (!File.Exists(lcPathFileNameServer))
779  {
780  _LogWebView($"No se ha encontrado en el servidor el fichero para la instalación del {RUNTIMEWEBVIEW}.");
781  return false;
782  }
783 
784  string lcTempPath = Path.GetTempPath();
785  string lcPathFileNameTemp = Path.Combine(lcTempPath, _cExecutableRuntime);
786 
787  if (File.Exists(lcPathFileNameTemp)) // Intentamos borrar el fichero del instalador si existe en el temp
788  File.Delete(lcPathFileNameTemp);
789 
790  ProcessStartInfo loExe = new ProcessStartInfo(lcPathFileNameServer); // Lo ejecutamos a partir de la ruta del servidor
791 
792  loExe.WorkingDirectory = lcTempPath; // Se realizará la descarga en el temp d
793  loExe.Arguments = @" /silent /install";
794  loProcess.StartInfo = loExe;
795  loProcess.StartInfo.CreateNoWindow = true;
796  loProcess.EnableRaisingEvents = true;
797  loExe.WindowStyle = ProcessWindowStyle.Hidden;
798 
799  try
800  {
801  llOk = loProcess.Start();
802  loProcess.WaitForExit();
803 
804  if (loProcess.ExitCode == 0)
805  _LogWebView($"Ha finalizado la instalación del {RUNTIMEWEBVIEW}.");
806  else
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.");
808  }
809  catch (Exception loEx)
810  {
811  _LogWebView($"Se ha producido un error al instalar el {RUNTIMEWEBVIEW}.{Environment.NewLine}{loEx.Message }.");
812  llOk = false;
813  }
814 
815  return llOk;
816  }
817 
821  private void DoInstallRuntime()
822  {
823  if (!_lBackgroudWorkerIsRunning)
824  {
825  _lBackgroudWorkerIsRunning = true;
826 
827  //Declaro un nuevo elemento
828  _oBackgroundWorker = new BackgroundWorker();
829 
830  //Configuro
831  _oBackgroundWorker.WorkerSupportsCancellation = true; // Permitimos realizar la cancelación
832  _oBackgroundWorker.WorkerReportsProgress = false;
833 
834  //Declaro los procesos
835  _oBackgroundWorker.DoWork += new DoWorkEventHandler(ExecuteRunWorker);
836  _oBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerCompleted);
837 
838  //Inicio la tarea asíncrona
839  _oBackgroundWorker.RunWorkerAsync();
840  }
841  }
842 
848  private void ExecuteRunWorker(object sender, DoWorkEventArgs e)
849  {
850  try
851  {
852  WebviewResultadoBackgroundWorker loResult = new WebviewResultadoBackgroundWorker();
853  loResult._Resultado = InstallRuntime();
854 
855  e.Result = loResult;
856  }
857  catch (Exception loEx)
858  {
859  _LogWebView($"Se ha producido un error al instalar {RUNTIMEWEBVIEW}.{Environment.NewLine}{loEx.Message }.");
860  }
861  }
862 
868  private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
869  {
870  if (e.Cancelled == false && e.Error == null && e.Result != null && e.Result is WebviewResultadoBackgroundWorker) //Sino he sido cancelado ni he registrado excepción
871  {
872  WebviewResultadoBackgroundWorker loWebviewResultadoBackgroundWorker = (WebviewResultadoBackgroundWorker)e.Result;
873 
874  _lRuntimeInstalled = loWebviewResultadoBackgroundWorker._Resultado;
875  }
876 
877  _lBackgroudWorkerIsRunning = false;
878  }
879  #endregion Métodos privados
880 
881  #region Métodos protected internal
882  protected internal void _NavigationStartingWebView()
886  {
887  _NavigationStarting?.Invoke();
888  }
889 
894  public virtual void _WebResourceResponseReceivedWebView(int tnHttpResponseStatusCode)
895  {
896  _WebResourceResponseReceived?.Invoke(tnHttpResponseStatusCode);
897  }
898 
904  protected internal void _NavigationCompletedWebView(string tcUrl, bool tlIsSuccess)
905  {
906  _NavigationCompleted?.Invoke(tcUrl, tlIsSuccess);
907  }
908 
915  protected internal void _MouseUpWebView(string tcTipo, string tcValue, string tcId)
916  {
917  _MouseUp?.Invoke(tcTipo, tcValue, tcId);
918 
919  _MouseUpExecute(tcTipo, tcValue, tcId);
920  }
921 
927  protected internal void _MouseDownWebView(string tcTipo, string tcValue)
928  {
929  _MouseDown?.Invoke(tcTipo, tcValue);
930  }
931 
935  protected internal void _MouseLeaveWebView()
936  {
937  _MouseLeave?.Invoke();
938  }
939 
944  protected internal void _LogWebView(string tcLog)
945  {
946  _Log?.Invoke(tcLog);
947 
948  _Mensaje_Error = tcLog;
949 
950  _Log_Analisis(tcLog);
951  }
952 
959  protected internal void _KeyPressWebView(KeyPressEventArgs e)
960  {
961  _KeyPress?.Invoke(e);
962  }
963 
969  protected internal void _ContentClickWebView(object sender, EventArgs e)
970  {
971  _ContentClick?.Invoke(sender, e);
972  }
973 
977  protected internal void _EndGetHTMWebView(string tcHtml)
978  {
979  _EndGetHTML?.Invoke(tcHtml);
980  }
981 
985  protected internal void _PrintBeforeWebView()
986  {
987  _PrintBefore?.Invoke();
988  }
989 
993  protected internal void _PrintAfterWebView()
994  {
995  _PrintAfter?.Invoke();
996  }
997 
998 
999  #endregion Métodos protected internal
1000 
1001  #region Métodos protected
1002  protected void _GetHtml()
1010  {
1011  if (_oWebView2 != null)
1012  _oWebView2._GetHtml();
1013  }
1014 
1019  protected void _ReadOnlyEditor(bool tlReadOnly)
1020  {
1021  if (_oWebView2 != null)
1022  _oWebView2._ReadOnlyEditor(tlReadOnly);
1023  }
1024 
1028  protected void _FocusEditor()
1029  {
1030  if (_oWebView2 != null)
1031  _oWebView2._FocusEditor();
1032  }
1033 
1038  protected void _PutDataEditor(string tcData)
1039  {
1040  if (_oWebView2 != null)
1041  _oWebView2._PutDataEditor(tcData);
1042  }
1043  #endregion Métodos protected
1044 
1045  #region Métodos public
1046  public void _InstallRuntime(string tcPath, string tcExecutable = "MicrosoftEdgeWebview2Setup.exe")
1053  {
1054  _LogWebView($"Se va a realizar la instalación del {RUNTIMEWEBVIEW}. (_InstallRuntime)");
1055 
1056  _cPathRuntime = tcPath;
1057  _cExecutableRuntime = tcExecutable;
1058 
1059  if (File.Exists(Path.Combine(_cPathRuntime, _cExecutableRuntime)))
1060  {
1061  _LogWebView($"Se va a realizara la instalación del {RUNTIMEWEBVIEW}. {_cPathRuntime}. (_InstallRuntime)");
1062 
1063  DoInstallRuntime();
1064  }
1065  else
1066  _LogWebView($"No existe el fichero de instalación del {RUNTIMEWEBVIEW} ({_cExecutableRuntime}) en la ruta {_cPathRuntime}.");
1067  }
1068 
1073  public void Navigate(string tcUrl)
1074  {
1075  if (_oWebView2 != null)
1076  _oWebView2.Navigate(tcUrl);
1077  else
1078  {
1079  Visibility();
1080  _LogWebView($"Se ha producido un error al navegar a la URL {tcUrl}.");
1081  }
1082  }
1083 
1089  public void NavigateToEditor(string tcUrl, string tcDataEditor)
1090  {
1091  if (_oWebView2 != null)
1092  _oWebView2.NavigateToEditor(tcUrl, tcDataEditor);
1093  else
1094  {
1095  Visibility();
1096  _LogWebView($"Se ha producido un error al navegar al a URL {tcUrl}. (NavigateEditor)");
1097  }
1098  }
1099 
1104  public void Navigate(Uri toUri)
1105  {
1106  if (_oWebView2 != null)
1107  _oWebView2.Navigate(toUri);
1108  else
1109  {
1110  Visibility();
1111  _LogWebView($"Se ha producido un error al navegar a la URL {toUri.AbsoluteUri}. ");
1112  }
1113  }
1114 
1120  public void NavigateToString(string tcHtmlContent)
1121  {
1122  if (_oWebView2 != null)
1123  _oWebView2.NavigateToString(tcHtmlContent);
1124  else
1125  {
1126  Visibility();
1127  _LogWebView("Se ha producido un error al cargar el HTML.");
1128  }
1129  }
1130 
1138  public void NavigateWithPost(string tcUrl, Stream toPostData, string tcHeaders = "Content-Type: application/x-www-form-urlencoded")
1139  {
1140  if (_oWebView2 != null)
1141  _oWebView2.NavigateWithPost(tcUrl, toPostData, tcHeaders);
1142  else
1143  {
1144  Visibility();
1145  _LogWebView($"Se ha producido un error al cargar la URL {tcUrl} por POST.");
1146  }
1147 
1148  }
1149  #endregion Métodos public
1150 
1151  #region Métodos protected virtual
1152  protected virtual void _Inicializar()
1156  {
1157  }
1158  #endregion Métodos protected virtual
1159 
1160  #region Métodos public virtual
1161  public virtual void _Log_Analisis(string tcLog)
1166  {
1167  }
1168 
1176  protected virtual bool _MouseUpExecute(string tcTipo, string tcValue, string tcIdOrName)
1177  {
1178  return true;
1179  }
1180  #endregion Métodos public virtual
1181 
1182  #region Estructura de resultados del BackGroundWorker
1183  public struct WebviewResultadoBackgroundWorker
1188  {
1192  public bool _Resultado;
1193  }
1194  #endregion Estructura de resultados del BackGroundWorker
1195 
1196  }
1197 }
_EndGetHTML_Handler _EndGetHTML
Finalización de la obtención del HTML del CKEDITOR
Definition: WebView.cs:142
void NavigateWithPost(string tcUrl, Stream toPostData, string tcHeaders="Content-Type: application/x-www-form-urlencoded")
Navigación POST
Definition: WebView.cs:1138
void DisableElementById(string tcId)
Método para desactivar un HtmlElement
Definition: WebView.cs:419
void Navigate(Uri toUri)
Navega a la URL del URI pasado por parámetro
Definition: WebView.cs:1104
_PrintBefore_Handler _PrintBefore
Evento al inició del métode _Print()
Definition: WebView.cs:164
void _FocusEditor()
Pasa el foco a la area de edición del CKEditor
Definition: WebView.cs:1028
void _Print(string tcTitulo="")
Imprime el contenido del navegador
Definition: WebView.cs:430
_MouseDown_Handler _MouseDown
Gestión de la pulsación sobre los htmlements de la página
Definition: WebView.cs:89
_NavigationCompleted_Handler _NavigationCompleted
Evento para capturar la finalización de la carga NavigationCompleted is raised when the WebView has c...
Definition: WebView.cs:66
virtual void _WebResourceResponseReceivedWebView(int tnHttpResponseStatusCode)
Método para poder capturar las respuestas
Definition: WebView.cs:894
WebView(bool tlValidateRuntime)
Constructor que valida si está instalado el Runtime del WebView
Definition: WebView.cs:198
_MouseUp_Handler _MouseUp
Gestión de la pulsación sobre los htmlements de la página
Definition: WebView.cs:79
UserControl WebView
Definition: WebView.cs:19
_KeyPress_Handler _KeyPress
Gestión de la pulsación de una tacla sobre la página
Definition: WebView.cs:120
void NavigateToString(string tcHtmlContent)
Navegación mediante el método NavigateToString
Definition: WebView.cs:1120
void _RefreshDocument()
Método para refrescar la instancia "Document" -> "HtmlDocument"
Definition: WebView.cs:409
_WebResourceResponseReceived_Handler _WebResourceResponseReceived
Evento de respuesta de recurso web recibido
Definition: WebView.cs:109
_Click_Handler _ContentClick
Evento de click en el contenido
Definition: WebView.cs:130
void _ReadOnlyEditor(bool tlReadOnly)
Establece el valor de ReadOnly del CKEditor
Definition: WebView.cs:1019
void Navigate(string tcUrl)
Navega a la URL del URI pasado por parámetro
Definition: WebView.cs:1073
_PrintAfter_Handler _PrintAfter
Evento al final del métode _Print()
Definition: WebView.cs:174
bool _Resultado
Resultado de la instalación en el BackGroundWorker
Definition: WebView.cs:1192
void _PutDataEditor(string tcData)
Añade un texto en una posición actual del curso dentro del CkEditor
Definition: WebView.cs:1038
_Log_Handler _Log
Gestión del Log
Definition: WebView.cs:153
void NavigateToEditor(string tcUrl, string tcDataEditor)
Navegar a la URL mediante el método Navigate
Definition: WebView.cs:1089
virtual bool _MouseUpExecute(string tcTipo, string tcValue, string tcIdOrName)
Método para gestionar el MouseUp
Definition: WebView.cs:1176
_MouseLeave_Handler _MouseLeave
Gestión para el mouseLeave el WebView2
Definition: WebView.cs:99
bool _IsRunTimeInstalled()
Devuelve si está instalado el Runtime del WebView
Definition: WebView.cs:571
dynamic _PrintAsync(string tcPrinterName, int tnCopies=0, string tcTitulo="")
Imprime el contenido del navegador
Definition: WebView.cs:441
void AddVirtualHostNameMapping(string alias, string ruta)
Método para establecer valores para crear alias de mapeo de rutas locales
Definition: WebView.cs:374