/// <summary> /// The post task. /// </summary> /// <param name="threadId"> /// The thread id. /// </param> /// <param name="action"> /// The action. /// </param> /// <param name="completionCallback"> /// The completion callback. /// </param> private void PostTask(CefThreadId threadId, Action <Action> action, Action completionCallback) { CefRuntime.PostTask(threadId, new ActionTask3(action, completionCallback)); }
// https://stackoverflow.com/questions/5769705/retrieving-embedded-resources-with-special-characters protected override ResourceResponse GetResourceResponse(ResourceRequest request) { var requestUrl = request.RequestUrl; var mainAssembly = Configuration.ResourceAssebmly; var response = new ResourceResponse(request); if (request.Method != Method.GET) { response.HttpStatus = System.Net.HttpStatusCode.NotFound; return(response); } var filePath = response.RelativePath; if (!string.IsNullOrEmpty(Configuration.RootPath)) { filePath = $"{Configuration.RootPath.Trim('/', '\\')}/{filePath}".Trim('/'); } var endTrimIndex = filePath.LastIndexOf('/'); if (endTrimIndex > -1) { var path = filePath.Substring(0, endTrimIndex); path = path.Replace("-", "_"); path = path.Replace("/", "."); if (Regex.IsMatch(path, "\\.(\\d+)")) { path = Regex.Replace(path, "\\.(\\d+)", "._$1"); } filePath = $"{path}{filePath.Substring(endTrimIndex)}"; } var resourceName = $"{mainAssembly.GetName().Name}.{filePath.Replace('/', '.')}"; Assembly satelliteAssembly = null; try { var fileInfo = new FileInfo(new Uri(mainAssembly.EscapedCodeBase).LocalPath); var satelliteFilePath = Path.Combine(fileInfo.DirectoryName, $"{Thread.CurrentThread.CurrentCulture}", $"{Path.GetFileNameWithoutExtension(fileInfo.Name)}.resources.dll"); if (File.Exists(satelliteFilePath)) { satelliteAssembly = mainAssembly.GetSatelliteAssembly(Thread.CurrentThread.CurrentCulture); } } catch { } var embeddedResources = mainAssembly.GetManifestResourceNames().Select(x => new { Target = mainAssembly, Name = x, IsSatellite = false }); if (satelliteAssembly != null) { string ProcessCultureName(string filename) => $"{Path.GetFileNameWithoutExtension(Path.GetFileName(filename))}.{Thread.CurrentThread.CurrentCulture.Name}{Path.GetExtension(filename)}"; embeddedResources = embeddedResources.Union(satelliteAssembly.GetManifestResourceNames().Select(x => new { Target = satelliteAssembly, Name = ProcessCultureName(x), IsSatellite = true })); } var resource = embeddedResources.SingleOrDefault(x => x.Name.Equals(resourceName, StringComparison.CurrentCultureIgnoreCase)); if (resource == null && !response.HasFileName) { foreach (var defaultFileName in SchemeOptions.DefaultFileName) { resourceName = string.Join(".", resourceName, defaultFileName); resource = embeddedResources.SingleOrDefault(x => x.Name.Equals(resourceName, StringComparison.CurrentCultureIgnoreCase)); if (resource != null) { break; } } } if (resource != null) { var manifestResourceName = resourceName; if (resource.IsSatellite) { manifestResourceName = $"{Path.GetFileNameWithoutExtension(Path.GetFileName(manifestResourceName))}{Path.GetExtension(manifestResourceName)}"; } var contenStream = resource?.Target?.GetManifestResourceStream(manifestResourceName); if (contenStream != null) { response.ContentStream = contenStream; response.MimeType = CefRuntime.GetMimeType(Path.GetExtension(resourceName).Trim('.')) ?? "text/plain"; return(response); } } response.HttpStatus = System.Net.HttpStatusCode.NotFound; return(response); }
public void AddPluginPath(string PluginPath) { CefRuntime.AddWebPluginPath(PluginPath); CefRuntime.RefreshWebPlugins(); }
/// <summary> /// The run internal. /// </summary> /// <param name="args"> /// The args. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> private int RunInternal(string[] args) { var tempFiles = CefBinariesLoader.Load(HostConfig); CefRuntime.EnableHighDpiSupport(); var assembly = Assembly.GetEntryAssembly() ?? typeof(ChromelyConfiguration).Assembly; var settings = new CefSettings { MultiThreadedMessageLoop = true, LogSeverity = (CefLogSeverity)HostConfig.LogSeverity, LogFile = HostConfig.LogFile, ResourcesDirPath = Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath) }; if (HostConfig.HostPlacement.Frameless || HostConfig.HostPlacement.KioskMode) { if (HostConfig.HostApi == ChromelyHostApi.Gtk) { throw new NotSupportedException("Chromely currently does not support frameless windows using GTK."); } // MultiThreadedMessageLoop is not allowed to be used as it will break frameless mode settings.MultiThreadedMessageLoop = false; } settings.LocalesDirPath = Path.Combine(settings.ResourcesDirPath, "locales"); settings.RemoteDebuggingPort = 20480; settings.NoSandbox = true; settings.Locale = HostConfig.Locale; if (HostConfig.UseDefaultSubprocess) { var subProcessExeFullPath = DefaultSubprocessExe.FulPath; settings.BrowserSubprocessPath = subProcessExeFullPath ?? settings.BrowserSubprocessPath; } var argv = args; if (CefRuntime.Platform != CefRuntimePlatform.Windows) { argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; } // Update configuration settings settings.Update(HostConfig.CustomSettings); var mainArgs = new CefMainArgs(argv); var app = new CefGlueApp(HostConfig); // CEF applications have multiple sub-processes (render, plugin, GPU, etc) // that share the same executable. This function checks the command-line and, // if this is a sub-process, executes the appropriate logic. var exitCode = CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero); if (exitCode >= 0) { // The sub-process has completed so return here. CefBinariesLoader.DeleteTempFiles(tempFiles); Log.Info($"Sub process executes successfully with code: {exitCode}"); return(exitCode); } // guard if something wrong foreach (var arg in args) { if (arg.StartsWith("--type=")) { return(-2); } } CefRuntime.Initialize(mainArgs, settings, app, IntPtr.Zero); RegisterSchemeHandlers(); RegisterMessageRouters(); Initialize(); _mainView = CreateMainView(); bool centerScreen = HostConfig.HostPlacement.CenterScreen; if (centerScreen) { _mainView.CenterToScreen(); } _windowCreated = true; IoC.RegisterInstance(typeof(IChromelyWindow), typeof(IChromelyWindow).FullName, this); CefBinariesLoader.DeleteTempFiles(tempFiles); RunMessageLoop(); _mainView.Dispose(); _mainView = null; CefRuntime.Shutdown(); Shutdown(); return(0); }
private void RunCallback() { CefRuntime.RunMessageLoop(); }
private void RegisterSchemes() { // register custom scheme handler CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory()); // CefRuntime.AddCrossOriginWhitelistEntry("http://localhost", "http", "", true); }
/// <summary> /// 主RUN函数 /// </summary> /// <param name="args"></param> /// <returns></returns> public int Run(string[] args) { //1.加载运行时 CefRuntime.Load(); //2.设置 var settings = new CefSettings(); settings.MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows; settings.ReleaseDCheckEnabled = true; settings.LogSeverity = CefLogSeverity.Verbose; settings.LogFile = "cef.log"; settings.ResourcesDirPath = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath); settings.RemoteDebuggingPort = 20480; //D:\01 project\3 FastQQ\xl\xilium-xilium.cefglue-820e4919a0f1\CefGlue.Client\bin\Debug\cache string cacahePath = @"D:\01 project\3 FastQQ\xl\xilium-xilium.cefglue-820e4919a0f1\CefGlue.Client\bin\Debug\cache"; // string cacahePath2 = Application.StartupPath+"\\cache"; settings.CachePath = cacahePath; // settings. var argv = args; if (CefRuntime.Platform != CefRuntimePlatform.Windows) { argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; } var mainArgs = new CefMainArgs(argv); var app = new DemoCefApp(); var exitCode = CefRuntime.ExecuteProcess(mainArgs, app); Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode); if (exitCode != -1) { return(exitCode); } // guard if something wrong foreach (var arg in args) { if (arg.StartsWith("--type=")) { return(-2); } } CefRuntime.Initialize(mainArgs, settings, app); // register custom scheme handler CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new DemoAppSchemeHandlerFactory()); // CefRuntime.RegisterSchemeHandlerFactory("http", Js2CsharpRequestDomain, new DemoAppSchemeHandlerFactory()); //AddCrossOriginWhitelistEntry 似乎没有用 //CefRuntime.AddCrossOriginWhitelistEntry( // "http://trade.taobao.com", "http", "https://tbapi.alipay.com", true); //CefRuntime.AddCrossOriginWhitelistEntry( // "http://trade.taobao.com", "https", "https://tbapi.alipay.com", true); //CefRuntime.AddCrossOriginWhitelistEntry( // string.Format("{0}", "tbapi.alipay.com"), "https", "", true); //alipay.com PlatformInitialize(); var mainMenu = CreateMainMenu(); _mainView = CreateMainView(mainMenu); _mainView.NewTab(HomeUrl); PlatformRunMessageLoop(); _mainView.Dispose(); _mainView = null; CefRuntime.Shutdown(); PlatformShutdown(); return(0); }
/// <summary> /// Shutdowns cef. /// </summary> private void ShutdownInternal() { CefRuntime.Shutdown(); GeneralLog.Info("CEF shutdown."); }
protected virtual IntPtr WndProc(IntPtr hWnd, uint message, IntPtr wParam, IntPtr lParam) { WM wmMsg = (WM)message; switch (wmMsg) { case WM.CREATE: { NativeInstance = this; _handle = hWnd; OnCreated(hWnd); var createdEvent = new CreatedEventArgs(_handle, _handle); HostCreated?.Invoke(this, createdEvent); _isInitialized = true; break; } case WM.ERASEBKGND: return(new IntPtr(1)); case WM.NCHITTEST: if (_options.WindowFrameless) { return((IntPtr)HT.CAPTION); } break; case WM.MOVING: case WM.MOVE: { HostMoving?.Invoke(this, new MovingEventArgs()); return(IntPtr.Zero); } case WM.SIZING: case WM.SIZE: { var size = GetClientSize(); OnSizeChanged(size.Width, size.Height); break; } case WM.GETMINMAXINFO: { if (HandleMinMaxSizes(lParam)) { return(IntPtr.Zero); } break; } case WM.CLOSE: { if (_handle != IntPtr.Zero && _isInitialized) { HostClose?.Invoke(this, new CloseEventArgs()); } DetachHooks(); DestroyWindow(_handle); break; } case WM.DESTROY: { if (_options.UseOnlyCefMessageLoop) { CefRuntime.QuitMessageLoop(); } PostQuitMessage(0); break; } default: break; } return(DefWindowProcW(hWnd, wmMsg, wParam, lParam)); }
private void ReleaseResources() { cefClient?.Dispose(); CefRuntime.Shutdown(); }
/// <summary> /// Starts CEF /// </summary> /// <exception cref="Exception"></exception> public void Init() { // ReSharper disable once RedundantAssignment string[] argv = args; #if LINUX //On Linux we need to do this, otherwise it will just crash, no idea why tho argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; #endif //Set up CEF args and the CEF app CefMainArgs cefMainArgs = new CefMainArgs(argv); BrowserProcessCEFApp cefApp = new BrowserProcessCEFApp(launchArguments); //Run our sub-processes int exitCode = CefRuntime.ExecuteProcess(cefMainArgs, cefApp, IntPtr.Zero); if (exitCode != -1) { Environment.Exit(exitCode); return; } //Backup if (argv.Any(arg => arg.StartsWith("--type="))) { Environment.Exit(-2); return; } //Do we have a cache or not, if not CEF will run in "incognito" mode. string cachePathArgument = null; if (launchArguments.CachePath != null) { cachePathArgument = launchArguments.CachePath.FullName; } //Convert UnityWebBrowser log severity to CefLogSeverity CefLogSeverity logSeverity = launchArguments.LogSeverity switch { LogSeverity.Debug => CefLogSeverity.Debug, LogSeverity.Info => CefLogSeverity.Info, LogSeverity.Warn => CefLogSeverity.Warning, LogSeverity.Error => CefLogSeverity.Error, LogSeverity.Fatal => CefLogSeverity.Fatal, _ => CefLogSeverity.Default }; //Setup the CEF settings CefSettings cefSettings = new CefSettings { WindowlessRenderingEnabled = true, NoSandbox = true, LogFile = launchArguments.LogPath.FullName, CachePath = cachePathArgument, //TODO: On MacOS multi-threaded message loop isn't supported MultiThreadedMessageLoop = true, LogSeverity = logSeverity, Locale = "en-US", ExternalMessagePump = false, RemoteDebuggingPort = launchArguments.RemoteDebugging, #if LINUX //On Linux we need to tell CEF where everything is, this will assume that the working directory is where everything is! ResourcesDirPath = System.IO.Path.Combine(Environment.CurrentDirectory), LocalesDirPath = System.IO.Path.Combine(Environment.CurrentDirectory, "locales"), BrowserSubprocessPath = Environment.GetCommandLineArgs()[0] #endif }; //Init CEF CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, IntPtr.Zero); //Create a CEF window and set it to windowless CefWindowInfo cefWindowInfo = CefWindowInfo.Create(); cefWindowInfo.SetAsWindowless(IntPtr.Zero, false); //Create our CEF browser settings CefColor backgroundColor = new CefColor(launchArguments.Bca, launchArguments.Bcr, launchArguments.Bcg, launchArguments.Bcb); CefBrowserSettings cefBrowserSettings = new CefBrowserSettings { BackgroundColor = backgroundColor, JavaScript = launchArguments.JavaScript ? CefState.Enabled : CefState.Disabled, LocalStorage = CefState.Disabled }; Logger.Debug($"CEF starting with these options:" + $"\nJS: {launchArguments.JavaScript}" + $"\nBackgroundColor: {backgroundColor}" + $"\nCache Path: {cachePathArgument}" + $"\nLog Path: {launchArguments.LogPath.FullName}" + $"\nLog Severity: {launchArguments.LogSeverity}"); Logger.Info("Starting CEF client..."); //Create cef browser cefClient = new BrowserProcessCEFClient(new CefSize(launchArguments.Width, launchArguments.Height), new ProxySettings(launchArguments.ProxyUsername, launchArguments.ProxyPassword, launchArguments.ProxyEnabled)); CefBrowserHost.CreateBrowser(cefWindowInfo, cefClient, cefBrowserSettings, launchArguments.InitialUrl); cefClient.OnUrlChange += OnUrlChange; }
private static int Main(string[] args) { try { CefRuntime.Load(); } catch (DllNotFoundException ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error); return(1); } catch (CefRuntimeException ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error); return(2); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error); return(3); } var mainArgs = new CefMainArgs(IntPtr.Zero, args); var cefApp = new SampleCefApp(); var exitCode = CefRuntime.ExecuteProcess(mainArgs, cefApp); if (exitCode != -1) { return(exitCode); } var cefSettings = new CefSettings { // BrowserSubprocessPath = browserSubprocessPath, SingleProcess = false, WindowlessRenderingEnabled = true, MultiThreadedMessageLoop = true, LogSeverity = CefLogSeverity.Verbose, LogFile = "cef.log", }; try { CefRuntime.Initialize(mainArgs, cefSettings, cefApp); } catch (CefRuntimeException ex) { MessageBox.Show(ex.ToString(), "Error!", MessageBoxButton.OK, MessageBoxImage.Error); return(4); } var app = new Xilium.CefGlue.Samples.WpfOsr.App(); app.InitializeComponent(); app.Run(); // shutdown CEF CefRuntime.Shutdown(); return(0); }
public void Start() { ManualResetEventSlim contextInitializedEvent = new ManualResetEventSlim(); dispatcher.PostTask(new Action(() => { CefRuntime.Load(); CefMainArgs cefMainArgs = new CefMainArgs(IntPtr.Zero, new String[0]); BrowserRuntimeSettings settings = BrowserSettings.Instance.RuntimeSettings; isMultiThreadedMessageLoop = settings.MultiThreadedMessageLoop; isSingleProcess = BrowserSettings.Instance.RuntimeSettings.SingleProcess; string browserSubprocessPath = Path.Combine(AssemblyDirectory, "CLRBrowserSourcePlugin", "CLRBrowserSourceClient.exe"); CefSettings cefSettings = new CefSettings { BrowserSubprocessPath = browserSubprocessPath, CachePath = settings.CachePath, CommandLineArgsDisabled = settings.CommandLineArgsDisabled, IgnoreCertificateErrors = settings.IgnoreCertificateErrors, JavaScriptFlags = settings.JavaScriptFlags, Locale = settings.Locale, LocalesDirPath = settings.LocalesDirPath, LogFile = settings.LogFile, LogSeverity = settings.LogSeverity, MultiThreadedMessageLoop = settings.MultiThreadedMessageLoop, NoSandbox = true, PersistSessionCookies = settings.PersistSessionCookies, ProductVersion = settings.ProductVersion, RemoteDebuggingPort = settings.RemoteDebuggingPort, ResourcesDirPath = settings.ResourcesDirPath, SingleProcess = false, UncaughtExceptionStackSize = settings.UncaughtExceptionStackSize, WindowlessRenderingEnabled = true }; string[] commandLineArgs = settings.CommandLineArgsDisabled ? new String[0] : settings.CommandLineArguments; BrowserApp browserApp = new BrowserApp( commandLineArgs, contextInitializedEvent); try { CefRuntime.Initialize(cefMainArgs, cefSettings, browserApp, IntPtr.Zero); } catch (InvalidOperationException e) { API.Instance.Log("Failed to initialize cef runtime"); contextInitializedEvent.Set(); } CefRuntime.RegisterSchemeHandlerFactory("local", null, new AssetSchemeHandlerFactory()); CefRuntime.RegisterSchemeHandlerFactory("http", "absolute", new AssetSchemeHandlerFactory()); if (!settings.MultiThreadedMessageLoop) { CefRuntime.RunMessageLoop(); } })); contextInitializedEvent.Wait(); }
/// <summary> /// The post task. /// </summary> /// <param name="threadId"> /// The thread id. /// </param> /// <param name="action"> /// The action. /// </param> /// <param name="flag"> /// The flag. /// </param> private void PostTask(CefThreadId threadId, Action <bool> action, bool flag) { CefRuntime.PostTask(threadId, new ActionTask4(action, flag)); }
/// <summary> /// The quit. /// </summary> public static void Quit() { CefRuntime.QuitMessageLoop(); }
public void RemovePlugin(string path) { CefRuntime.RemoveWebPluginPath(path); CefRuntime.RefreshWebPlugins(); }
public static void Initialize(string cachePath = null, string paragonPath = null, string browserLanguage = null, string authserverlist = null, string authdelgatelist = null, bool disableSpellChecking = false, bool ignoreCertificateErrors = false, bool persistSessionCookies = false) { if (IsInitialized) { Logger.Debug("CEF initialization aborted because it is already initialized ."); return; } using (AutoStopwatch.TimeIt("Initializing runtime")) { if (Interlocked.CompareExchange(ref _cefInitializing, 1, 0) == 1) { Logger.Debug("CEF initialization aborted because initialization is in progress"); return; } Logger.Debug("CEF is initializing"); MainThreadContext = SynchronizationContext.Current; try { var logPath = "cef.log"; _initThread = Thread.CurrentThread.ManagedThreadId; if (!string.IsNullOrEmpty(cachePath)) { logPath = Path.Combine(cachePath, logPath); cachePath = Path.Combine(cachePath, "cache"); } var rendererPath = paragonPath ?? Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "paragon.renderer.exe"); if (!File.Exists(rendererPath)) { rendererPath = Path.Combine(Environment.CurrentDirectory, "paragon.renderer.exe"); } if (!File.Exists(rendererPath)) { throw new CefRuntimeException("Unable to determine the path to paragon.renderer.exe"); } var binPath = Path.GetDirectoryName(rendererPath); if (!File.Exists(Path.Combine(binPath, "libcef.dll"))) { throw new CefRuntimeException("Unable to determine the path to libcef.dll"); } var settings = new CefSettings { SingleProcess = false, MultiThreadedMessageLoop = true, IgnoreCertificateErrors = ignoreCertificateErrors, LogSeverity = CefLogSeverity.Default, LogFile = logPath, BrowserSubprocessPath = rendererPath, Locale = browserLanguage, CachePath = cachePath, PersistSessionCookies = persistSessionCookies, AuthServerWhitelist = authserverlist, AuthDelegateWhitelist = authdelgatelist, ProductVersion = string.Format("Paragon/{0} Chrome/{1}", Assembly.GetExecutingAssembly().GetName().Version, CefRuntime.ChromeVersion) }; var argArray = Environment.GetCommandLineArgs(); List <string> appArgs = new List <string>(); appArgs.Add("--process-per-tab"); // Pass through Kerberos and proxy parameters. for (int i = 0; i < argArray.Length; i++) { string a = argArray[i]; if (a.StartsWith("--enable-logging") || a.StartsWith("--v=") || a.Contains("proxy")) { appArgs.Add(a); } } var argString = string.Join(",", appArgs.ToArray()); Logger.Info("Passing Args to CefApp: " + argString); var args = new CefMainArgs(appArgs.ToArray()); _cefApp = new CefBrowserApplication(disableSpellChecking, browserLanguage); _cefApp.RenderProcessInitialize += OnRenderProcessInitialize; if (BeforeCefInitialize != null) { var ea = new CefInitializationEventArgs(); BeforeCefInitialize(null, ea); settings.LogFile = ea.LogFile; settings.LogSeverity = ea.LogSeverity; if (ea.RemoteDebuggingPort > 0) { settings.RemoteDebuggingPort = ea.RemoteDebuggingPort; } } CefRuntime.Load(); var result = CefRuntime.ExecuteProcess(args, _cefApp, IntPtr.Zero); if (result == -1) { CefRuntime.Initialize(args, settings, _cefApp, IntPtr.Zero); Interlocked.Exchange(ref _cefInitialized, 1); Logger.Info("CEF initialized successfully"); } else { throw new CefRuntimeException("CEF initialization failed - CefRuntime.ExecuteProcess return code: " + result); } } catch (CefRuntimeException) { throw; } catch (Exception e) { Logger.Error("Error initializing CEF: " + e); throw; } finally { Interlocked.Exchange(ref _cefInitializing, 0); if (!IsInitialized && _cefApp != null) { _cefApp = null; } } } }
public int Initialize() { if (initialized) { if (!created) { CreateBrowser(); } return(0); } CefRuntime.Load(); var settings = new CefSettings(); settings.MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows; settings.ReleaseDCheckEnabled = true; settings.SingleProcess = true; settings.PersistSessionCookies = true; settings.CommandLineArgsDisabled = false; settings.ContextSafetyImplementation = CefContextSafetyImplementation.SafeDefault; settings.IgnoreCertificateErrors = true; settings.ResourcesDirPath = "/res"; settings.PackLoadingDisabled = false; settings.LogSeverity = CefLogSeverity.Default; settings.LogFile = "cef.log"; settings.ResourcesDirPath = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath); settings.RemoteDebuggingPort = 9000; settings.UserAgent = browserSettings.UserAgent; settings.Locale = browserSettings.Locale; settings.LocalesDirPath = browserSettings.LocaleDirPath; settings.CachePath = browserSettings.CachePath; var args = new string[] { }; var argv = args; if (CefRuntime.Platform != CefRuntimePlatform.Windows) { argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; } var mainArgs = new CefMainArgs(argv); Global.app = new ClientApp(); Global.app.SetBrowserControl(Global.instance); var exitCode = CefRuntime.ExecuteProcess(mainArgs, Global.app); Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode); if (exitCode != -1) { return(exitCode); } foreach (var arg in args) { if (arg.StartsWith("--type=")) { return(-2); } } CefRuntime.Initialize(mainArgs, settings, Global.app); CefRuntime.RegisterSchemeHandlerFactory("http", DumpRequestDomain, new AppSchemeHandlerFactory()); bool b = CefRuntime.AddCrossOriginWhitelistEntry("http://localhost", "http", "", true); CreateBrowser(); initialized = true; return(0); }
private int RunInternal(string[] args) { CefRuntime.Load(); var settings = new CefSettings(); settings.MultiThreadedMessageLoop = MultiThreadedMessageLoop = CefRuntime.Platform == CefRuntimePlatform.Windows; settings.SingleProcess = false; settings.LogSeverity = CefLogSeverity.Verbose; settings.LogFile = "cef.log"; settings.ResourcesDirPath = System.IO.Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetEntryAssembly().CodeBase).LocalPath); settings.RemoteDebuggingPort = 20480; settings.NoSandbox = true; var argv = args; if (CefRuntime.Platform != CefRuntimePlatform.Windows) { argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; } var mainArgs = new CefMainArgs(argv); var app = new DemoCefApp(); var exitCode = CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero); Console.WriteLine("CefRuntime.ExecuteProcess() returns {0}", exitCode); if (exitCode != -1) { return(exitCode); } // guard if something wrong foreach (var arg in args) { if (arg.StartsWith("--type=")) { return(-2); } } CefRuntime.Initialize(mainArgs, settings, app, IntPtr.Zero); RegisterSchemes(); RegisterMessageRouter(); PlatformInitialize(); var mainMenu = CreateMainMenu(); _mainView = CreateMainView(mainMenu); _mainView.NewTab(HomeUrl); PlatformRunMessageLoop(); _mainView.Dispose(); _mainView = null; CefRuntime.Shutdown(); PlatformShutdown(); return(0); }
public void Run() { RunMessageLoopInternal(); CefRuntime.Shutdown(); }
/// <summary> /// The post task. /// </summary> /// <param name="threadId"> /// The thread id. /// </param> /// <param name="action"> /// The action. /// </param> private static void PostTask(CefThreadId threadId, Action action) { CefRuntime.PostTask(threadId, new ActionTask(action)); }
private static int Main(string[] args) { try { try { CefRuntime.Load(); } catch (DllNotFoundException ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return(1); } catch (CefRuntimeException ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return(2); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return(3); } var mainArgs = new CefMainArgs(args); var app = new CefApplication(); int exitCode = CefRuntime.ExecuteProcess(mainArgs, app); if (exitCode != -1) { return(exitCode); } var settings = new CefSettings { SingleProcess = false, MultiThreadedMessageLoop = true, LogSeverity = CefLogSeverity.Disable, LogFile = "CefGlue.log", }; CefRuntime.Initialize(mainArgs, settings, app); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!settings.MultiThreadedMessageLoop) { Application.Idle += (sender, e) => { CefRuntime.DoMessageLoopWork(); }; } InitDevExpress(); UpdateHelper.ForcedUpdate(); Application.ThreadException += Application_ThreadException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; BaseSystemInfo.StartupPath = Application.StartupPath; BaseSystemInfo.CustomerCompanyName = "申通快递"; BaseSystemInfo.SoftFullName = "申通打印专家"; BaseSystemInfo.SoftName = BaseSystemInfo.SoftFullName; BaseSystemInfo.MailUserName = "******"; BaseSystemInfo.MailServer = "smtp.qq.com"; BaseSystemInfo.MailPassword = "******"; BaseSystemInfo.SystemCode = "ZTOPrint"; // ZipFile(); Synchronous.Synchronous.BeforeLogOn(); // new FrmWaiting().ShowDialog(); CheckPrinterWindowsServer(); CheckInitData(); var t = new Task(() => ComputerHelper.GetServerDataTime()); t.Start(); // Application.Run(new FrmLogOnByMobile()); Application.Run(new FrmMain()); return(0); } catch (Exception ex) { LogUtil.WriteException(ex); MessageBox.Show(ex.Message); } CefRuntime.Shutdown(); return(0); }
protected int RunInternal(string[] args) { MacHostRuntime.LoadNativeHostFile(_config); _config.ChromelyVersion = CefRuntime.ChromeVersion; var tempFiles = CefBinariesLoader.Load(_config); CefRuntime.EnableHighDpiSupport(); _settings = new CefSettings { MultiThreadedMessageLoop = (_config.Platform == ChromelyPlatform.Windows && !_config.WindowOptions.UseOnlyCefMessageLoop), LogSeverity = CefLogSeverity.Info, LogFile = "logs\\chromely.cef_" + DateTime.Now.ToString("yyyyMMdd") + ".log", ResourcesDirPath = _config.AppExeLocation }; _settings.LocalesDirPath = Path.Combine(_settings.ResourcesDirPath, "locales"); _settings.RemoteDebuggingPort = 20480; _settings.Locale = "en-US"; _settings.NoSandbox = true; var argv = args; if (CefRuntime.Platform != CefRuntimePlatform.Windows) { argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; } // Update configuration settings _settings.Update(_config.CustomSettings); // For Windows- if MultiThreadedMessageLoop is overriden in Setting using CustomSettings, then // It is assumed that the developer way not be aware of IWindowOptions - UseOnlyCefMessageLoop if (_config.Platform == ChromelyPlatform.Windows) { _config.WindowOptions.UseOnlyCefMessageLoop = !_settings.MultiThreadedMessageLoop; } // Set DevTools url string devtoolsUrl = _config.DevToolsUrl; if (string.IsNullOrWhiteSpace(devtoolsUrl)) { _config.DevToolsUrl = $"http://127.0.0.1:{_settings.RemoteDebuggingPort}"; } else { Uri uri = new Uri(devtoolsUrl); if (uri.Port <= 80) { _config.DevToolsUrl = $"{devtoolsUrl}:{_settings.RemoteDebuggingPort}"; } } ResolveHandlers(); var mainArgs = new CefMainArgs(argv); CefApp app = CreateApp(); if (ClientAppUtils.ExecuteProcess(_config.Platform, argv)) { // CEF applications have multiple sub-processes (render, plugin, GPU, etc) // that share the same executable. This function checks the command-line and, // if this is a sub-process, executes the appropriate logic. var exitCode = CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero); if (exitCode >= 0) { // The sub-process has completed so return here. Logger.Instance.Log.LogInformation($"Sub process executes successfully with code: {exitCode}"); return(exitCode); } } CefRuntime.Initialize(mainArgs, _settings, app, IntPtr.Zero); _window.RegisterHandlers(); RegisterDefaultSchemeHandlers(); RegisterCustomSchemeHandlers(); CefBinariesLoader.DeleteTempFiles(tempFiles); _window.Init(_settings); MacHostRuntime.EnsureNativeHostFileExists(_config); NativeHost_CreateAndShowWindow(); NativeHost_Run(); CefRuntime.Shutdown(); NativeHost_Quit(); return(0); }
void IStartable.Shutdown() { CefRuntime.Shutdown(); }
private void ShutdownCallback() { CefRuntime.Shutdown(); }
private int RunInternal(string[] args) { Initialize(); _config.ChromelyVersion = CefRuntime.ChromeVersion; var tempFiles = CefBinariesLoader.Load(_config.CefDownloadOptions, _config.Platform); CefRuntime.EnableHighDpiSupport(); var settings = new CefSettings { MultiThreadedMessageLoop = _config.Platform == ChromelyPlatform.Windows, LogSeverity = CefLogSeverity.Info, LogFile = "logs\\chromely.cef_" + DateTime.Now.ToString("yyyyMMdd") + ".log", ResourcesDirPath = _config.AppExeLocation }; if (_config.WindowOptions.WindowFrameless || _config.WindowOptions.KioskMode) { // MultiThreadedMessageLoop is not allowed to be used as it will break frameless mode settings.MultiThreadedMessageLoop = false; } settings.LocalesDirPath = Path.Combine(settings.ResourcesDirPath, "locales"); settings.RemoteDebuggingPort = 20480; settings.Locale = "en-US"; settings.NoSandbox = true; var argv = args; if (CefRuntime.Platform != CefRuntimePlatform.Windows) { argv = new string[args.Length + 1]; Array.Copy(args, 0, argv, 1, args.Length); argv[0] = "-"; } // Update configuration settings settings.Update(_config.CustomSettings); // Set DevTools url _config.DevToolsUrl = $"http://127.0.0.1:{settings.RemoteDebuggingPort}"; var mainArgs = new CefMainArgs(argv); CefApp app = new CefGlueApp(_config); if (ClientAppUtils.ExecuteProcess(_config.Platform, argv)) { // CEF applications have multiple sub-processes (render, plugin, GPU, etc) // that share the same executable. This function checks the command-line and, // if this is a sub-process, executes the appropriate logic. var exitCode = CefRuntime.ExecuteProcess(mainArgs, app, IntPtr.Zero); if (exitCode >= 0) { // The sub-process has completed so return here. Logger.Instance.Log.Info($"Sub process executes successfully with code: {exitCode}"); return(exitCode); } } CefRuntime.Initialize(mainArgs, settings, app, IntPtr.Zero); ScanAssemblies(); RegisterRoutes(); RegisterMessageRouters(); RegisterResourceHandlers(); RegisterSchemeHandlers(); RegisterAjaxSchemeHandlers(); CefBinariesLoader.DeleteTempFiles(tempFiles); CreateMainWindow(); Run(); _mainWindow.Dispose(); _mainWindow = null; Shutdown(); return(0); }
public void Free() { CefRuntime.Shutdown(); }
/// <summary> /// The run. /// </summary> public static void Run() { /* run the GTK+ main loop */ CefRuntime.RunMessageLoop(); }
public void AddPluginDir(string PluginDir) { CefRuntime.AddWebPluginDirectory(PluginDir); CefRuntime.RefreshWebPlugins(); }
/// <summary> /// The post task. /// </summary> /// <param name="threadId"> /// The thread id. /// </param> /// <param name="action"> /// The action. /// </param> /// <param name="port"> /// The port. /// </param> /// <param name="completionCallback"> /// The completion callback. /// </param> private void PostTask(CefThreadId threadId, Action <int, Action> action, int port, Action completionCallback) { CefRuntime.PostTask(threadId, new ActionTask2(action, port, completionCallback)); }