diff --git a/BrowseForFileAndFolder/BrowseForFileAndFolder.csproj b/BrowseForFileAndFolder/BrowseForFileAndFolder.csproj index 66e155e..fe4a623 100644 --- a/BrowseForFileAndFolder/BrowseForFileAndFolder.csproj +++ b/BrowseForFileAndFolder/BrowseForFileAndFolder.csproj @@ -1,96 +1,20 @@ - - - + - Debug - AnyCPU - {74EA2D69-AF51-4BC9-A531-335219379E2A} + net472 WinExe - BrowseForFileAndFolder - BrowseForFileAndFolder - v4.7.2 - 512 - true - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 + false + true + true - true bin\x86\Debug\ - DEBUG;TRACE - full - x86 - 7.3 - prompt - true bin\x86\Release\ - TRACE - true - pdbonly - x86 - 7.3 - prompt - true - - ..\packages\CoreWindowsWrapper.2.0.3\lib\net472\CoreWindowsWrapper.dll - - - ..\packages\Diga.Core.Api.Win32.2.0.6\lib\net472\Diga.Core.Api.Win32.dll - - - - - - - - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - - - - + + + - \ No newline at end of file diff --git a/Diga.NativeControls.WebBrowser.Core/Diga.NativeControls.WebBrowser.csproj b/Diga.NativeControls.WebBrowser.Core/Diga.NativeControls.WebBrowser.csproj index d20b4f4..5e55157 100644 --- a/Diga.NativeControls.WebBrowser.Core/Diga.NativeControls.WebBrowser.csproj +++ b/Diga.NativeControls.WebBrowser.Core/Diga.NativeControls.WebBrowser.csproj @@ -12,15 +12,39 @@ WebBrowserControl build with WebView2 and CoreWindowsWrapper true Diga.NativeControls.WebBrowser - 1.1.24 - 1.1.24 + 1.1.25 + 1.1.25 https://github.com/ITAgnesmeyer/WebAssemblyViewer https://github.com/ITAgnesmeyer/Diga.NativeControls - 1.1.24 + 1.1.25 logo.png true + + 1701;1702;CA1416 + + + + 1701;1702;CA1416 + + + + 1701;1702;CA1416 + + + + 1701;1702;CA1416 + + + + 1701;1702;CA1416 + + + + 1701;1702;CA1416 + + @@ -28,12 +52,13 @@ - - + + - - - + + + + diff --git a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Events.cs b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Events.cs index e6fedda..82bab91 100644 --- a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Events.cs +++ b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Events.cs @@ -244,11 +244,33 @@ protected virtual void OnFrameNavigationCompleted(NavigationCompletedEventArgs e FrameNavigationCompleted?.Invoke(this, e); } + private static void BeforeProcessExitCatch(object sender, EventArgs e) + { + Debug.Print("BeforeProcessExitCatch"); + DateTime n = DateTime.Now; + DateTime x = DateTime.Now; + TimeSpan diff = x - n; + while (diff.Seconds < 5) + { + UIDispatcher.UIThread.DoEvents(); + x = DateTime.Now; + diff = x - n; + } + } protected virtual void OnBeforeWebViewDestroy() { try { BeforeWebViewDestroy?.Invoke(this, EventArgs.Empty); + ControlCounter--; + if (ControlCounter <= 0) + { + //UIDispatcher.Wait(5000); + #if !NETCOREAPP3_1_OR_GREATER + //AppDomain.CurrentDomain.ProcessExit += BeforeProcessExitCatch; + #endif + UIDispatcher.FilnalDisposed = true; + } } catch (Exception ex) { @@ -310,7 +332,7 @@ protected virtual void OnDomContentLoaded(DOMContentLoadedEventArgs e) protected virtual void OnWebResourceResponseReceived(WebResourceResponseReceivedEventArgs e) { WebResourceResponseReceived?.Invoke(this, e); - CleanUpResponses(e); + //CleanUpResponses(e); } diff --git a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Monitoring.cs b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Monitoring.cs index 58267d9..f35ba45 100644 --- a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Monitoring.cs +++ b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Monitoring.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Diagnostics; using System.IO; +using Diga.WebView2.Monitoring; using Diga.WebView2.Wrapper; using Diga.WebView2.Wrapper.EventArguments; using MimeTypeExtension; @@ -10,214 +11,269 @@ namespace Diga.NativeControls.WebBrowser { public partial class NativeWebBrowser { - private readonly ConcurrentDictionary - _Responses = new ConcurrentDictionary(); + //private readonly ConcurrentDictionary + // _Responses = new ConcurrentDictionary(); + private MonitoringActionList _MonitoringActionList; private void CheckMonitoring(WebResourceRequestedEventArgs e) { - if (this.EnableMonitoring) + string uri = e.Request.Uri; + if (this._MonitoringActionList.IsAnyActiveWithUrl(uri)) { - //Debug.Print("url request=>" + e.Request.Uri); - if (GetFileStream(e.Request.Uri, out var responseInfo)) + var action = this._MonitoringActionList.GetFirstActiveWithUrl(uri); + RequestInfo requestInfo = new RequestInfo(e.Request); + try { - var response = this.CreateResponse(responseInfo); - e.Response = response; - this._Responses.TryAdd(e.Request.Uri, responseInfo); - //Debug.Print("Open response:" + this._Responses.Count); - } - } - - if (GetResource(e.Request.Uri, out var responseInfoRes)) - { - var response = this.CreateResponse(responseInfoRes); - e.Response = response; - this._Responses.TryAdd(e.Request.Uri, responseInfoRes); - } - - } - - private bool GetResource(string url, out ResponseInfo responseInfo) - { - string monUrl = "https://diga.assets:1/"; - - if (!url.StartsWith(monUrl)) - { - responseInfo = null; - return false; - } - - if (url.Length <= monUrl.Length) - { - responseInfo = null; - return false; - } - string resName = url.Substring(monUrl.Length); + if (action.Run(requestInfo, out var responseInfo)) + { + var respose = this.CreateResponse(responseInfo); + e.Response = respose; - if (string.IsNullOrEmpty(resName)) - { - responseInfo = null; - return false; - } + } - try - { - string resString = "";//Resources.ResourceManager.GetString(resName); - if (resString == null) - { - responseInfo = new ResponseInfo("

Server Error

file not found:" + url + "
"); - responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); - responseInfo.ContentType = "content-type: text/html; charset=utf-8"; - responseInfo.StatusCode = 404; - responseInfo.StatusText = "Not Found"; - return false; } - - int index = resString.IndexOf("base64,", StringComparison.Ordinal); - string mime = resString.Substring(5, index - 5); - - string contentBase64 = resString.Substring(index + 7); - - byte[] contentBase64Bytes = Convert.FromBase64String(contentBase64); - - - responseInfo = new ResponseInfo(contentBase64Bytes); - responseInfo.Header.Add("content-type", mime); - responseInfo.ContentType = mime; - responseInfo.StatusCode = 200; - responseInfo.StatusText = "OK"; - return true; - } - catch (Exception e) - { - string message = "Error:" + e.Message; - responseInfo = new ResponseInfo(message); - responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); - responseInfo.ContentType = "content-type; charset=utf-8"; - responseInfo.StatusCode = 500; - responseInfo.StatusText = "Internal Server Error"; - return true; - } - - - - - - } - private void CleanUpResponses(WebResourceResponseReceivedEventArgs e) - { - try - { - if (this._Responses.ContainsKey(e.Request.Uri)) + catch (Exception exception) { - if (this._Responses.TryRemove(e.Request.Uri, out var resp)) - { - resp.Dispose(); - } - + Console.WriteLine(exception); + throw; } - - } - catch (Exception exception) - { - Debug.Print("CleanUpResponse Error:" + exception.Message); - } - } - - private bool MonitoringFileExist(string file) - { - if (file.StartsWith("/")) - file = file.Substring(1); - file = file.Replace("/", "\\"); - string fullName = Path.Combine(this.MonitoringFolder, file); - return File.Exists(fullName); - } - private bool GetFileStream(string url, out ResponseInfo responseInfo) - { - if (!url.StartsWith(this.MonitoringUrl)) - { - responseInfo = null; - return false; - } - - Uri uri = new Uri(url); - - - //TestMimeTypes(); - string baseDirectory = this.MonitoringFolder; - - string file = MonitoringFileExist(uri.AbsolutePath) ? uri.AbsolutePath : ""; - - if (file == "/") - file = ""; - if (file.StartsWith("/")) - file = file.Substring(1); - if (string.IsNullOrEmpty(file)) - file = "index.html"; - file = file.Replace("/", "\\"); - file = Path.Combine(baseDirectory, file); - FileInfo fileInfo = new FileInfo(file); - if (!fileInfo.Exists) - { - responseInfo = new ResponseInfo("

Server Error

file not found:" + file + "
"); - responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); - responseInfo.ContentType = "content-type: text/html; charset=utf-8"; - responseInfo.StatusCode = 404; - responseInfo.StatusText = "Not Found"; - - return false; - } - - string contentType = fileInfo.MimeTypeOrDefault(); - if (contentType == "document") - Debug.Print(contentType); - try - { - byte[] bytes = File.ReadAllBytes(file); - responseInfo = new ResponseInfo(bytes); - string utf8Extension = GetUtf8IfNeeded(contentType); - - responseInfo.Header.Add("content-type", contentType + utf8Extension); - - responseInfo.ContentType = "content-type: " + contentType + utf8Extension; - responseInfo.StatusCode = 200; - responseInfo.StatusText = "OK"; - - return true; - } - catch (Exception e) - { - string message = "Error:" + e.Message; - responseInfo = new ResponseInfo(message); - responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); - responseInfo.ContentType = "content-type; charset=utf-8"; - responseInfo.StatusCode = 500; - responseInfo.StatusText = "Internal Server Error"; - return true; } } - private static string GetUtf8IfNeeded(string contentType) - { - if (string.IsNullOrEmpty(contentType)) - return ""; - - bool needUtf8 = false; - - switch (contentType) - { - case "application/x-javascript": - case "text/html": - case "text/css": - case "application/javascript": - case "application/json": - needUtf8 = true; - break; - } - - if (needUtf8) - return "; charset=utf-8"; - return ""; - } + //private void CheckMonitoring(WebResourceRequestedEventArgs e) + //{ + + // string uri = e.Request.Uri; + // bool isMonitroingUrl = IsMonitoringUrl(uri); + // bool isResourceUrl = IsResorceUrl(uri); + // if (isMonitroingUrl || isResourceUrl) + // { + // RequestInfo requestInfo = new RequestInfo(e.Request); + + // if (isMonitroingUrl) + // { + // if (GetMonitoringFile(requestInfo, out var responseInfo)) + // { + // var response = this.CreateResponse(responseInfo); + // e.Response = response; + // return; + // } + // } + + + // if (isResourceUrl) + // { + // if (GetResource(requestInfo, out var responseInfoRes)) + // { + // var response = this.CreateResponse(responseInfoRes); + // e.Response = response; + + // //return; + // } + // } + // } + //} + + //private bool IsResorceUrl(string url) + //{ + // if (string.IsNullOrEmpty(url)) + // return false; + // if (url.StartsWith("diga://")) + // return true; + // return false; + + //} + + //private bool IsMonitoringUrl(string url) + //{ + // if (!this.EnableMonitoring) + // return false; + // if (string.IsNullOrEmpty(url)) + // return false; + // if (url.StartsWith(this.MonitoringUrl)) + // return true; + // return false; + //} + //private bool GetResource(RequestInfo requestInfo, out ResponseInfo responseInfo) + //{ + // string url = requestInfo.Uri; + // string monUrl = "diga://"; + + // if (!url.StartsWith(monUrl)) + // { + // responseInfo = null; + // return false; + // } + + // if (url.Length <= monUrl.Length) + // { + // responseInfo = null; + // return false; + // } + // string resName = url.Substring(monUrl.Length); + + // if (string.IsNullOrEmpty(resName)) + // { + // responseInfo = null; + // return false; + // } + + // try + // { + // string resString = Resources.ResourceManager.GetString(resName); + // if (resString == null) + // { + // responseInfo = new ResponseInfo("

Server Error

file not found:" + url + "
"); + // responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); + // responseInfo.ContentType = "content-type: text/html; charset=utf-8"; + // responseInfo.StatusCode = 404; + // responseInfo.StatusText = "Not Found"; + // return false; + // } + + // int index = resString.IndexOf("base64,", StringComparison.Ordinal); + // string mime = resString.Substring(5, index - 5); + + // string contentBase64 = resString.Substring(index + 7); + + // byte[] contentBase64Bytes = Convert.FromBase64String(contentBase64); + + + // responseInfo = new ResponseInfo(contentBase64Bytes); + // responseInfo.Header.Add("content-type", mime); + // responseInfo.ContentType = mime; + // responseInfo.StatusCode = 200; + // responseInfo.StatusText = "OK"; + // return true; + // } + // catch (Exception e) + // { + // string message = "Error:" + e.Message; + // responseInfo = new ResponseInfo(message); + // responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); + // responseInfo.ContentType = "content-type; charset=utf-8"; + // responseInfo.StatusCode = 500; + // responseInfo.StatusText = "Internal Server Error"; + // return true; + // } + + //} + ////private void CleanUpResponses(WebResourceResponseReceivedEventArgs e) + ////{ + //// //try + //// //{ + //// // if (this._Responses.ContainsKey(e.Request.Uri)) + //// // { + //// // if (this._Responses.TryRemove(e.Request.Uri, out var resp)) + //// // { + //// // resp.Dispose(); + //// // } + + //// // } + + //// //} + //// //catch (Exception exception) + //// //{ + //// // Debug.Print("CleanUpResponse Error:" + exception.Message); + //// //} + ////} + + //private bool MonitoringFileExist(string file) + //{ + // if (file.StartsWith("/")) + // file = file.Substring(1); + // file = file.Replace("/", "\\"); + // string fullName = Path.Combine(this.MonitoringFolder, file); + // return File.Exists(fullName); + //} + //private bool GetMonitoringFile(RequestInfo requestInfo, out ResponseInfo responseInfo) + //{ + // string url = requestInfo.Uri; + // if (!url.StartsWith(this.MonitoringUrl)) + // { + // responseInfo = null; + // return false; + // } + + // Uri uri = new Uri(url); + + + // //TestMimeTypes(); + // string baseDirectory = this.MonitoringFolder; + + // string file = MonitoringFileExist(uri.AbsolutePath) ? uri.AbsolutePath : ""; + + // if (file == "/") + // file = ""; + // if (file.StartsWith("/")) + // file = file.Substring(1); + // if (string.IsNullOrEmpty(file)) + // file = "index.html"; + // file = file.Replace("/", "\\"); + // file = Path.Combine(baseDirectory, file); + // FileInfo fileInfo = new FileInfo(file); + // if (!fileInfo.Exists) + // { + // responseInfo = new ResponseInfo("

Server Error

file not found:" + file + "
"); + // responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); + // responseInfo.ContentType = "content-type: text/html; charset=utf-8"; + // responseInfo.StatusCode = 404; + // responseInfo.StatusText = "Not Found"; + + // return false; + // } + + // string contentType = fileInfo.MimeTypeOrDefault(); + // if (contentType == "document") + // Debug.Print(contentType); + // try + // { + // byte[] bytes = File.ReadAllBytes(file); + // responseInfo = new ResponseInfo(bytes); + // string utf8Extension = GetUtf8IfNeeded(contentType); + + // responseInfo.Header.Add("content-type", contentType + utf8Extension); + + // responseInfo.ContentType = "content-type: " + contentType + utf8Extension; + // responseInfo.StatusCode = 200; + // responseInfo.StatusText = "OK"; + + // return true; + // } + // catch (Exception e) + // { + // string message = "Error:" + e.Message; + // responseInfo = new ResponseInfo(message); + // responseInfo.Header.Add("content-type", "text/html; charset=utf-8"); + // responseInfo.ContentType = "content-type; charset=utf-8"; + // responseInfo.StatusCode = 500; + // responseInfo.StatusText = "Internal Server Error"; + // return true; + // } + //} + + //private static string GetUtf8IfNeeded(string contentType) + //{ + // if (string.IsNullOrEmpty(contentType)) + // return ""; + + // bool needUtf8 = false; + + // switch (contentType) + // { + // case "application/x-javascript": + // case "text/html": + // case "text/css": + // case "application/javascript": + // case "application/json": + // needUtf8 = true; + // break; + // } + + // if (needUtf8) + // return "; charset=utf-8"; + // return ""; + //} } } diff --git a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Properties.cs b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Properties.cs index a402733..7ff2e8e 100644 --- a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Properties.cs +++ b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Properties.cs @@ -1,5 +1,8 @@ using System.Collections.Generic; +using System.ComponentModel; using System.Drawing; +using System.Threading.Tasks; +using Diga.WebView2.Interop; using Diga.WebView2.Wrapper; using Diga.WebView2.Wrapper.Types; @@ -7,7 +10,7 @@ namespace Diga.NativeControls.WebBrowser { public partial class NativeWebBrowser { - private bool _DefaultContextMenusEnabled = true; + private bool _DefaultContextMenusEnabled; private string _Url; private bool _DefaultScriptDialogsEnabled = true; @@ -19,29 +22,149 @@ public partial class NativeWebBrowser private bool _IsScriptEnabled = true; private bool _IsStatusBarEnabled; private bool _IsWebMessageEnabled = true; - private bool _AreBrowserAcceleratorKeysEnabled = true; - private bool _IsGeneralAutoFillEnabled = true; - private bool _IsPasswordAutosaveEnabled = true; + private bool _IsGeneralAutoFillEnabled; + private bool _IsPasswordAutosaveEnabled; + private string _HtmlContent; private double _ZoomFactor; - public bool AutoDock { get; set; } = false; public string BrowserExecutableFolder { get; set; } = ""; public string BrowserUserDataFolder { get; set; } = ""; public string BrowserAdditionArgs { get; set; } = ""; - public string MonitoringFolder { get; set; } = ""; - public string MonitoringUrl { get; set; } = ""; - public bool EnableMonitoring { get; set; } = false; - private Color _DefaultBackgroundColor = Color.Empty; + private SchemeRegistration[] _SchemeRegistrations; + + #region Public Properties + private string _MonitoringFolder; + //[Editor(typeof(FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] + public string MonitoringFolder + { + get + { + return _MonitoringFolder; + } + set + { + _MonitoringFolder = value; + this._MonitoringActionList.FileMonitoring.SetMonitoringFolder(_MonitoringFolder); + } + } + private string _MonitoringUrl; + public string MonitoringUrl + { + get + { + return _MonitoringUrl; + } + set + { + _MonitoringUrl = value; + + this._MonitoringActionList.FileMonitoring.SetMonitoringUrl(_MonitoringUrl); + } + } + + private bool _EnableMonitoring; + public bool EnableMonitoring + { + get + { + return this._EnableMonitoring; + } + set + { + this._EnableMonitoring = value; + this._MonitoringActionList.FileMonitoring.SetIsEnabled(value); + } + } + + private bool _EnableCgi; + public bool EnableCgi + { + get + { + return this._EnableCgi; + } + set + { + this._EnableCgi = value; + this._MonitoringActionList.CgiMointoring.SetIsEnabled(value); + } + } + + private string _CgiMonitoringUrl; + public string CgiMoitoringUrl + { + get + { + return this._CgiMonitoringUrl; + } + set + { + this._CgiMonitoringUrl = value; + this._MonitoringActionList.CgiMointoring.SetMonitoringUrl(value); + } + } + + private string _CgiMoitoringFolder; + //[Editor(typeof(FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] + public string CgiMoitoringFolder + { + get + { + return _CgiMoitoringFolder; + } + set + { + this._CgiMoitoringFolder = value; + this._MonitoringActionList.CgiMointoring.SetMonitoringFolder(value); + } + } + + private string[] _CgiFileExtensions; + + public string[] CgiFileExtensions + { + get + { + return this._CgiFileExtensions; + } + set + { + this._CgiFileExtensions = value; + this._MonitoringActionList.CgiMointoring.SetCgiExtionsions(value); + + } + } + private string _CgiExeFile; + //[Editor(typeof(ExeSelectFileNameEditor), typeof(System.Drawing.Design.UITypeEditor))] + public string CgiExeFile + { + get + { + return this._CgiExeFile; + } + set + { + this._CgiExeFile = value; + this._MonitoringActionList.CgiMointoring.SetCgiExeFile(value); + } + } public string Url { get => this._Url; - set => this._Url = value; + set + { + this._Url = value; + if (this.CheckIsCreatedOrEnded) + { + Navigate(value); + } + } } public List Content @@ -69,40 +192,32 @@ public Color DefaultBackgroundColor this._DefaultBackgroundColor = this._WebViewControl.DefaultBackgroundColor; } - return _DefaultBackgroundColor; + return this._DefaultBackgroundColor; } set { - _DefaultBackgroundColor = value; + this._DefaultBackgroundColor = value; if (this.CheckIsCreatedOrEnded) { - this._WebViewControl.DefaultBackgroundColor = _DefaultBackgroundColor; + this._WebViewControl.DefaultBackgroundColor = this._DefaultBackgroundColor; } - } } + public Task PageSource => GetDocumentTextAsync(); + + [Browsable(false)] public string DocumentTitle { - get - { - if (this.CheckIsCreatedOrEnded) - return this._WebViewControl.DocumentTitle; - return ""; - } + get => this._WebViewControl.DocumentTitle; } public string HtmlContent { get => this._HtmlContent; - set - { - - this.NavigateToString(value); - - } + set => NavigateToString(value); } public bool IsZoomControlEnabled @@ -227,8 +342,9 @@ public bool RemoteObjectsAllowed } } - public bool IsCreated { get; set; } - public bool IsBrowserEnded { get; private set; } = false; + [Browsable(false)] public bool IsCreated { get; private set; } + + [Browsable(false)] public bool IsBrowserEnded { get; private set; } public bool DevToolsEnabled { @@ -319,6 +435,12 @@ public CookieManager GetCookieManager public WebView2Environment Environment => this._WebViewControl.Environment; public WebView2View WebView2 => this._WebViewControl.WebView; + public SchemeRegistration[] SchemeRegistrations + { + get => this._SchemeRegistrations; + set => this._SchemeRegistrations = value; + } + public bool CanGoBack { get @@ -338,7 +460,6 @@ public bool CanGoForward return false; } } - - + #endregion } } \ No newline at end of file diff --git a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Scripting.cs b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Scripting.cs index e3c41b3..9ffd157 100644 --- a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Scripting.cs +++ b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.Scripting.cs @@ -10,7 +10,7 @@ namespace Diga.NativeControls.WebBrowser { public partial class NativeWebBrowser { - private RpcHandler _RpcHandler; + private RpcHandler _RpcHandler; private const string JAVASCRIPT_CANNOT_BE_NULL_OR_EMPTY = "javaScript cannot be NULL or empty"; diff --git a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.cs b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.cs index d599f16..32261ad 100644 --- a/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.cs +++ b/Diga.NativeControls.WebBrowser.Core/NativeWebBrowser.cs @@ -1,8 +1,11 @@ using System; +using System.Diagnostics; +using System.Drawing; using System.Runtime.CompilerServices; using CoreWindowsWrapper; using Diga.Core.Api.Win32; using Diga.Core.Threading; +using Diga.WebView2.Monitoring; using Diga.WebView2.Scripting; using Diga.WebView2.Wrapper; using Diga.WebView2.Wrapper.EventArguments; @@ -18,12 +21,14 @@ public partial class NativeWebBrowser : NativeControlBase //private const string JAVASCRIPT_CANNOT_BE_NULL_OR_EMPTY = "javaScript cannot be NULL or empty"; private NativeWindow _ParentNativeWindow = null; private WebView2Control _WebViewControl; + private static int ControlCounter = 0; protected override void Initialize() { this._RpcHandler = new RpcHandler(); this._RpcHandler.RpcEvent += OnRpcEventIntern; this._RpcHandler.RpcDomUnloadEvent += OnRpcDomUnloadEvent; + this._MonitoringActionList = new MonitoringActionList(); base.Initialize(); this.ControlType = CoreWindowsWrapper.Win32ApiForm.ControlType.Label; this.TypeIdentifier = "static"; @@ -31,16 +36,62 @@ protected override void Initialize() this.BackColor = CoreWindowsWrapper.Tools.ColorTool.White; this.ForeColor = CoreWindowsWrapper.Tools.ColorTool.Black; } + private int HiWord(int number) + { + if ((number & 0x80000000) == 0x80000000) + return (number >> 16); + return (number >> 16) & 0xffff; + } + private int LoWord(int number) + { + return number & 0xffff; + } + protected override bool ControlProc(IntPtr hWndParent, IntPtr hWndControl, int controlId, uint command, IntPtr wParam, IntPtr lParam) + { + if (command == 0x210) + { + if (wParam.ToInt32() == 0x204) + { + int lp = lParam.ToInt32(); + int x = HiWord(lp); + int y = LoWord(lp); + OnMouseButtonDown(new WebViewButtonDownEventArgs(new System.Drawing.Point(x,y))); + } + } + return base.ControlProc(hWndParent, hWndControl, controlId, command, wParam, lParam); + } + + private void CreateWebViewControl(IntPtr parent) + { + try + { + if (UIDispatcher.FilnalDisposed) + { + UIDispatcher.FilnalDisposed = false; + +//#if !NETCOREAPP3_1_OR_GREATER + //AppDomain.CurrentDomain.ProcessExit -= BeforeProcessExitCatch; +//#endif + } + + + this._WebViewControl = new WebView2Control(parent,this.BrowserExecutableFolder, this.BrowserUserDataFolder, this.BrowserAdditionArgs); + WireEvents(this._WebViewControl); + ControlCounter++; + } + catch (Exception ex) + { + Debug.Print(nameof(CreateWebViewControl) + " Exception:" + ex); + } + } public override bool Create(IntPtr parentId) { bool created = base.Create(parentId); if (this.Handle != IntPtr.Zero) { - this._WebViewControl = new WebView2Control(this.Handle, this.BrowserExecutableFolder, this.BrowserUserDataFolder, this.BrowserAdditionArgs); - WireEvents(this._WebViewControl); - + CreateWebViewControl(this.Handle); } else @@ -76,6 +127,31 @@ private void WebWindowInitSettings(BeforeCreateEventArgs e) } + private void WebWindowInitAction() + { + this.IsCreated = true; + AddRemoteObject("RpcHandler", this._RpcHandler); + AddScriptToExecuteOnDocumentCreated( + "class ScriptErrorObject{constructor(e,t,r,n,i,c){this.name=e,this.message=t,this.fileName=r,this.lineNumber=n,this.columnNumber=i,this.stack=c}}window.external={sendMessage:function(e){window.chrome.webview.postMessage(e)},receiveMessage:function(e){window.chrome.webview.addEventListener(\"message\",(function(t){e(t.data)}))},evalScript:function(e){try{return eval(e)}catch(e){let t=new ScriptErrorObject(e.name,e.message,e.fileName,e.lineNumber,e.columnNumber,e.stack);return JSON.stringify(t)}},executeScript:function(e){try{return new Function(e)()}catch(e){let t=new ScriptErrorObject(e.name,e.message,e.fileName,e.lineNumber,e.columnNumber,e.stack);return JSON.stringify(t)}}};"); + AddScriptToExecuteOnDocumentCreated( + "window.external.raiseRpcEvent= async function(action, obj,objName,eventObj) { if(window.diga == undefined) window.diga = new Object(); try { const rpcHandler = window.chrome.webview.hostObjects.RpcHandler;const rpcObj = await rpcHandler.GetNewRpc(); let vn=await rpcObj.idName;window.diga[vn]=eventObj;rpcObj.objId = obj.id;rpcObj.action = action;rpcObj.varname=objName; rpcObj.param = \"empty\";rpcObj.item=document.getElementById(obj.id);let r = await rpcHandler.Handle(await rpcObj.id, await rpcObj.action, rpcObj);let b = await rpcHandler.ReleaseObject(rpcObj); } catch (e) { alert(e); } }; console.log('script_loaded'); window.addEventListener(\"beforeunload\",(e)=>{ window.chrome.webview.hostObjects.sync.RpcHandler.UnloadDom(); });"); + + //"window.external = { sendMessage: function(message) { window.chrome.webview.postMessage(message); }, receiveMessage: function(callback) { window.chrome.webview.addEventListener('message', function(e) { callback(e.data); }); } };"); + if (this._DefaultBackgroundColor != Color.Empty) + this._WebViewControl.DefaultBackgroundColor = this._DefaultBackgroundColor; + if (!string.IsNullOrEmpty(this._Url)) + Navigate(this.Url); + if (!string.IsNullOrEmpty(this._HtmlContent)) + NavigateToString(this._HtmlContent); + if (this._ZoomFactor != 0) + this.ZoomFactor = this._ZoomFactor; + //this._WebViewControl.SetVirtualHostNameToFolderMapping("diga.resources","c:\\temp",COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_ALLOW); + } + + private void OnParentSize(object sender, SizeEventArgs e) + { + this.DoDock(); + } public void DoDock() { @@ -109,28 +185,6 @@ public void DoDock() } - private void WebWindowInitAction() - { - this.IsCreated = true; - this.IsBrowserEnded = false; - - AddScriptToExecuteOnDocumentCreated( - "class ScriptErrorObject{constructor(e,t,r,n,i,c){this.name=e,this.message=t,this.fileName=r,this.lineNumber=n,this.columnNumber=i,this.stack=c}}window.external={sendMessage:function(e){window.chrome.webview.postMessage(e)},receiveMessage:function(e){window.chrome.webview.addEventListener(\"message\",(function(t){e(t.data)}))},evalScript:function(e){try{return eval(e)}catch(e){let t=new ScriptErrorObject(e.name,e.message,e.fileName,e.lineNumber,e.columnNumber,e.stack);return JSON.stringify(t)}},executeScript:function(e){try{return new Function(e)()}catch(e){let t=new ScriptErrorObject(e.name,e.message,e.fileName,e.lineNumber,e.columnNumber,e.stack);return JSON.stringify(t)}}};"); - AddScriptToExecuteOnDocumentCreated( - "window.external.raiseRpcEvent= async function(action, obj,objName,eventObj) { if(window.diga == undefined) window.diga = new Object(); try { const rpcHandler = window.chrome.webview.hostObjects.RpcHandler;const rpcObj = await rpcHandler.GetNewRpc(); let vn=await rpcObj.idName;window.diga[vn]=eventObj;rpcObj.objId = obj.id;rpcObj.action = action;rpcObj.varname=objName; rpcObj.param = \"empty\";rpcObj.item=document.getElementById(obj.id);let r = await rpcHandler.Handle(await rpcObj.id, await rpcObj.action, rpcObj);let b = await rpcHandler.ReleaseObject(rpcObj); } catch (e) { alert(e); } }; console.log('script_loaded'); window.addEventListener(\"beforeunload\",(e)=>{ window.chrome.webview.hostObjects.sync.RpcHandler.UnloadDom(); });"); - - //"window.external = { sendMessage: function(message) { window.chrome.webview.postMessage(message); }, receiveMessage: function(callback) { window.chrome.webview.addEventListener('message', function(e) { callback(e.data); }); } };"); - //if (this._DefaultBackgroundColor != Color.Empty) - // this._WebViewControl.DefaultBackgroundColor = this._DefaultBackgroundColor; - if (!string.IsNullOrEmpty(this._Url)) - Navigate(this.Url); - if (!string.IsNullOrEmpty(this._HtmlContent)) - NavigateToString(this._HtmlContent); - if (this._ZoomFactor != 0) - this.ZoomFactor = this._ZoomFactor; - AddRemoteObject("RpcHandler", this._RpcHandler); - //this._WebViewControl.SetVirtualHostNameToFolderMapping("diga.resources","c:\\temp",COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_ALLOW); - } private bool CheckIsCreatedOrEnded { @@ -151,31 +205,10 @@ private void CheckIsCreatedOrEndedWithThrow() private void CheckIsInUiThread([CallerMemberName] string member = "") { - if (!UIDispatcher.UIThread.CheckAccess()) + if (!this.UIDispatcher.CheckAccess()) throw new InvalidOperationException($"method ({member}) can only execute on UI-Thread"); } - - - - //public WebResourceResponse CreateResponse(ResponseInfo responseInfo) - //{ - // WebResourceResponse response = null; - // if (this.CheckIsCreatedOrEnded) - // { - // response = this._WebViewControl.GetResponseStream(responseInfo.Stream, responseInfo.StatusCode, - // responseInfo.StatusText, responseInfo.HeaderToString(), responseInfo.ContentType); - // } - - // return response; - //} - - - private void OnParentSize(object sender, SizeEventArgs e) - { - this.DoDock(); - } - private UIDispatcher UIDispatcher => UIDispatcher.UIThread; diff --git a/DigaCoreTest/DigaCoreTest.csproj b/DigaCoreTest/DigaCoreTest.csproj index 4dbccf0..8f23696 100644 --- a/DigaCoreTest/DigaCoreTest.csproj +++ b/DigaCoreTest/DigaCoreTest.csproj @@ -12,7 +12,7 @@ - + diff --git a/DigaWinFormsTest/DigaWinFormsTest.csproj b/DigaWinFormsTest/DigaWinFormsTest.csproj index 7af05c7..84cebe8 100644 --- a/DigaWinFormsTest/DigaWinFormsTest.csproj +++ b/DigaWinFormsTest/DigaWinFormsTest.csproj @@ -1,111 +1,26 @@ - - - + - Debug - AnyCPU - {FD503648-6928-4AC9-8CD5-B9F83899AD03} + net472;net6.0-windows WinExe - DigaWinFormsTest - DigaWinFormsTest - v4.7.2 - 512 - true - true - - + false + true + true - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\packages\CoreWindowsWrapper.2.0.3\lib\net472\CoreWindowsWrapper.dll - - - ..\packages\Diga.Core.Api.Win32.2.0.6\lib\net472\Diga.Core.Api.Win32.dll - - - ..\packages\Diga.WebView2.Interop.20.1.1\lib\netstandard2.0\Diga.WebView2.Interop.dll - - - ..\packages\Diga.WebView2.Wrapper.20.1.1\lib\netstandard2.0\Diga.WebView2.Wrapper.dll - - - ..\packages\MimeTypeExtension.1.0.29\lib\netstandard2.0\MimeTypeExtension.dll - - - ..\packages\Newtonsoft.Json.13.0.2\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - - - - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - - - + - - {1df3378f-8286-4c29-974b-0deb58958368} - Diga.NativeControls.WebBrowser - + + + + + + + + + - xcopy /S /Y $(SolutionDir)wwwroot\* $(TargetDir)wwwroot\* - - - - Dieses Projekt verweist auf mindestens ein NuGet-Paket, das auf diesem Computer fehlt. Verwenden Sie die Wiederherstellung von NuGet-Paketen, um die fehlenden Dateien herunterzuladen. Weitere Informationen finden Sie unter "http://go.microsoft.com/fwlink/?LinkID=322105". Die fehlende Datei ist "{0}". - - - \ No newline at end of file