示例#1
0
        static void Main()
        {
#if NETCOREAPP3_1
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());
            WinFormium.CreateRuntimeBuilder(env =>
            {
                env.CustomCefSettings(settings =>
                {
                });

                env.CustomCefCommandLineArguments(commandLine =>
                {
                });
            }, app =>
            {
                app.UseEmbeddedFileResource("http", "www.app.local", "wwwroot");

                app.UseDataServiceResource("http", "api.app.local");

                //app.UseDebuggingMode();

                app.UseMainWindow(context => new MainWindow());
            }).Build().Run();
        }
示例#2
0
        static void Main()
        {
#if NETCOREAPP3_1_OR_GREATER
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WinFormium.CreateRuntimeBuilder(env =>
            {
                env.CustomCefSettings(settings =>
                {
                    // Sets this property to true, if you are attempting to use Layerd/Acrylic style.
                    settings.WindowlessRenderingEnabled = true;
                });

                env.CustomCefCommandLineArguments(commandLine =>
                {
                });
            }, app =>
            {
                app.UseDebuggingMode();

                app.UseEmbeddedFileResource("http", "res.app.local", "wwwroot");

                app.UseMainWindow(context => new MainWindow());
            }).Build().Run();
        }
示例#3
0
        internal static void Setup(ChromeWidgetMessageInterceptor interceptor, Formium formium, Func <Message, bool> forwardAction)
        {
            Task.Run(() =>
            {
                try
                {
                    while (true)
                    {
                        if (BrowserWidgetHandleFinder.TryFindHandle(formium.BrowserWindowHandle, out IntPtr chromeWidgetHostHandle))
                        {
                            interceptor = new ChromeWidgetMessageInterceptor(formium.HostWindowInternal, chromeWidgetHostHandle, forwardAction);

                            if (WinFormium.Runtime.IsDebuggingMode)
                            {
                                WinFormium.GetLogger().Debug("BrowserWindow has been attached successfully.");
                            }

                            break;
                        }
                        else
                        {
                            Thread.Sleep(100);
                        }
                    }
                }
                catch
                {
                }
            });
        }
示例#4
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            WinFormium.CreateRuntimeBuilder(env =>
            {
                env.CustomCefSettings(settings =>
                {
                    // 在此处设置 CEF 的相关参数
                });

                env.CustomCefCommandLineArguments(commandLine =>
                {
                    // 在此处指定 CEF 命令行参数
                });
            }, app =>
            {
                //注册嵌入ZIP程序集资源处理器
                app.UseZippedResource("http", "archive.app.local", () => new MemoryStream(Properties.Resources.dist));
                // 指定启动窗体
                app.UseMainWindow(context => new MainWindow());
            })
            .Build()
            .Run();
        }
示例#5
0
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);

            try
            {
                WindowUtils.EnableAcrylic(this);
            }
            catch (Exception ex)
            {
                WinFormium.GetLogger().Error(ex);
            }
        }
示例#6
0
        static void Main()
        {
#if NETCOREAPP3_1_OR_GREATER
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            WinFormium.CreateRuntimeBuilder(env =>
            {
                env.CustomCefSettings(settings =>
                {
                });

                env.CustomCefCommandLineArguments(commandLine =>
                {
                });
            }, app =>
            {
                app.UseDebuggingMode();

                app.UseMainWindow(context => new MainWindow());
            }).Build().Run();
        }
示例#7
0
        static void Main()
        {
#if NETCOREAPP3_1_OR_GREATER
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif

            WinFormium.CreateRuntimeBuilder(env =>
            {
                // You should do some initializing staffs of Cef Environment in this function.

                env.CustomCefCommandLineArguments(cmdLine =>
                {
                    // Configure command line arguments of Cef here.

                    //cmdLine.AppendSwitch("disable-gpu");
                    //cmdLine.AppendSwitch("disable-gpu-compositing");
                });

                env.CustomCefSettings(settings =>
                {
                    // Configure default Cef settings here.
                    settings.WindowlessRenderingEnabled = true;
                });

                env.CustomDefaultBrowserSettings(cefSettings =>
                {
                    // Configure default browser settings here.
                });
            },
                                            app =>
            {
                // You can configure your application settings of NanUI here.
#if DEBUG
                // Use this setting if your application running in DEBUG mode, it will allow user to open or clode DevTools by right-clicking mouse button and selecting menu items on context menu.
                //app.UseDebuggingMode();
#endif

                // Use this setting if you want only one instance can be run.
                app.UseSingleInstance(() =>
                {
                    MessageBox.Show("Instance has already run, only one instance can be run.", "Single Instance", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                });

                // Register JavaScript Extension by using this method. More info about JavaScript Extension please see the JavaScript Extension chapter in documentation of NanUI.
                app.RegisterJavaScriptExtension(() => new DemoWindowJavaScriptExtension());

                // Clear all cached files such as cookies, histories, localstorages, etc.
                app.ClearCacheFile();

                app.UseEmbeddedFileResource("http", "main.app.local", "wwwroot");

                // Register LocalFileResource handler which can handle the file resources in local folder.
                app.UseLocalFileResource("http", "static.app.local", System.IO.Path.Combine(Application.StartupPath, "LocalFiles"));

                // Register UseZippedResource handler which can handle the resources zipped in archives.
                // Use the following method to load zip file in Resource file of current assembly.
                app.UseZippedResource("http", "acrylic.example.local", () => new System.IO.MemoryStream(Properties.Resources.AcrylicDemoResource));

                // Or use the code below to load zip file from disk.
                app.UseZippedResource("http", "layered.example.local", System.IO.Path.Combine(Application.StartupPath, "LayeredDemoResource.zip"));

                // Register DataServiceResource handler which can process http request and return data to response.
                // It will find all DataServices in current assembly automatically or you can indicate where to find the DataServices by using the third parameter.
                app.UseDataServiceResource("https", "api.app.local");;

                // Set a main window class inherit Formium here to start appliation message loop.
                app.UseMainWindow(context =>
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    // You should return a Formium instatnce here or you can use context.MainForm property to set a Form which does not inherit Formium.

                    // context.MainForm = new Form();

                    return(new MainForm());
                });

                // If your application doesn't have a main window such as VSTO applicaitons, you could use this to initialize NanUI and CEF.
                //app.UseApplicationContext(() => new ApplicationContext());
            })
            // Build the NanUI runtime
            .Build()
            // Run the main process
            .Run();
        }
        private void AcceptClient(NamedPipeServerStream pipe)
        {
            Task.Run(() =>
            {
                try
                {
                    var buff = new byte[BUFFER_SIZE];
                    var ms   = new MemoryStream();

                    do
                    {
                        ms.Write(buff, 0, pipe.Read(buff, 0, buff.Length));
                    }while (!pipe.IsMessageComplete);

                    var body = Encoding.UTF8.GetString(ms.ToArray());

                    ms.Close();
                    ms.Dispose();
                    buff = null;

                    var request = MessageBridgeRequest.Create(body);

                    MessageBridgeResponse response = null;

                    foreach (var handler in JavascriptBridge.JavascriptRequestHandlers)
                    {
                        try
                        {
                            var retval = handler?.Invoke(request);
                            if (retval != null)
                            {
                                response = retval;
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            response = MessageBridgeResponse.CreateFailureResponse(ex.Message);
                        }
                    }

                    if (response == null)
                    {
                        response = MessageBridgeResponse.CreateFailureResponse("Can't found handler for this request.");
                    }
                    buff = Encoding.UTF8.GetBytes(response.ToJson());
                    try
                    {
                        pipe.Write(buff, 0, buff.Length);
                        pipe.Flush();
                        pipe.WaitForPipeDrain();
                    }
                    catch (Exception ex)
                    {
                        WinFormium.GetLogger().Debug($"NamedPipeServer can't write to client. {ex.Message}");
                    }
                    finally
                    {
                        pipe.Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    WinFormium.GetLogger().Error(ex);
                }
            }, CancellationToken);
        }
        public Main()
            : base("http://res.app.local/index.html")
        {
            InitializeComponent();

            MainForm = this;

            LoadHandler.OnLoadEnd += HtmlLoadEnd;

            GlobalObject.AddFunction("ShowDevTools").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    Chromium.ShowDevTools();
                });
            };

            GlobalObject.AddFunction("ChangeSerialConnection").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    string portName = args.Arguments[0].StringValue;
                    if (SerialPortManager.Device.IsOpen)
                    {
                        SerialPortManager.Close();
                    }
                    else
                    {
                        SerialPortManager.Open(portName);
                    }
                    args.SetReturnValue(SerialPortManager.Device.IsOpen);
                });
            };

            GlobalObject.AddFunction("ChangeConnectionState").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    bool state = args.Arguments[0].BoolValue;
                    if (state)
                    {
                        ConnectionManager.Start();
                    }
                    else
                    {
                        ConnectionManager.Stop();
                    }
                });
            };

            GlobalObject.AddFunction("ReconnectDevice").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    ConnectionManager.Start();
                });
            };

            GlobalObject.AddFunction("RefreshClick").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    bool ret = false;
                    try
                    {
                        DataManager.Params.Clear();
                        string deal = PortAgreement.ReadAllCard();
                        SerialPortManager.Write(deal);
                        OverTimer.start();

                        ret = true;
                    }
                    catch (Exception ex)
                    {
                        Log4Helper.ErrorInfo(ex.Message, ex);
                        JavascriptEvent.ErrorMessage(ex.Message);
                    }
                    args.SetReturnValue(ret);
                });
            };


            GlobalObject.AddFunction("DownloadClick").Execute += (func, args) =>
            {
                int count = DataManager.Params.Where(e => e.State != "设置成功" && e.DataType == "正常").Count();
                if (count == 0)
                {
                    args.SetReturnValue(count);
                    return;
                }
                this.RequireUIThread(() =>
                {
                    string strClientNumber = args.Arguments[0].StringValue;

                    Task.Factory.StartNew(() =>
                    {
                        foreach (Param item in DataManager.Params)
                        {
                            if (item.State != "设置成功" && item.DataType == "正常")
                            {
                                string deal = PortAgreement.WriteClientNumber(item.CardNumber, strClientNumber);
                                bool ret    = SerialPortManager.Write(deal);
                                if (ret)
                                {
                                    SerialPortManager.OperationResult = OperationResults.None;
                                    for (int i = 0; i < 500; i++)
                                    {
                                        Thread.Sleep(10);
                                        if (SerialPortManager.OperationResult != OperationResults.None)
                                        {
                                            if (SerialPortManager.OperationResult == OperationResults.Success)
                                            {
                                                item.State = "设置成功";

                                                DataManager.ViewListDisplay();
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        JavascriptEvent.OperationOver();
                    });
                });
                args.SetReturnValue(-1);
            };

            GlobalObject.AddFunction("SetDeviceClient").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    string strClientNumber = args.Arguments[0].StringValue;
                    string deal            = PortAgreement.EncryptionDevice(strClientNumber);
                    bool ret = SerialPortManager.Write(deal);
                    args.SetReturnValue(ret);
                });
            };

            GlobalObject.AddFunction("SetCardNumber").Execute += (func, args) =>
            {
                this.RequireUIThread(() =>
                {
                    string strOldNumber  = args.Arguments[0].StringValue;
                    string strCardNumber = args.Arguments[1].StringValue;
                    string strType       = args.Arguments[2].StringValue;
                    string deal          = PortAgreement.WriteCardNumber(strOldNumber, strCardNumber, strType);
                    bool ret             = SerialPortManager.Write(deal);
                    if (ret)
                    {
                        if (strCardNumber != "797979" || strCardNumber != "123456")
                        {
                            ConfigManager.SetConfig("Number", strCardNumber);
                        }
                    }
                    args.SetReturnValue(ret);
                });
            };
        }
示例#10
0
文件: Program.cs 项目: maxjove/NanUI
        static void Main(string[] args)
        {
#if NETCOREAPP3_1 || NET5_0
            Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
#endif
            //bool createNew;
            //using (System.Threading.Mutex m = new System.Threading.Mutex(true, Application.ProductName, out createNew))
            //{
            //    if (!createNew)
            //    {
            //        MessageBox.Show("只能运行一个实例!");
            //        return;
            //    }
            //}
            //MessageBox.Show("只能运行一个实例!");

            Application.ThreadException -= new ThreadExceptionEventHandler(Application_ThreadException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            //MainForm mfrm = null;
            WinFormium.CreateRuntimeBuilder(env =>
            {
                // You should do some initializing staffs of Cef Environment in this function.

                env.CustomCefCommandLineArguments(cmdLine =>
                {
                    // // Configure command line arguments of Cef here.

                    // //cmdLine.AppendSwitch("disable-gpu");
                    // //cmdLine.AppendSwitch("disable-gpu-compositing");
                    //cmdLine.AppendSwitch("disable-web-security");
                    //cmdLine.AppendSwitch("unsafely-treat-insecure-origin-as-secure", Wnconfig.GetUrl());
                    //cmdLine.AppendSwitch("enable-media-stream", "1");
                    // //cmdLine.AppendSwitch("disable-gpu-watchdog");
                    // //cmdLine.AppendSwitch("disable-gpu-shader-disk-cache");
                    // //cmdLine.AppendSwitch("no-crash-upload");
                    // //cmdLine.AppendSwitch("disable-breakpad");
                    // //--disk-cache-size=xxx
                    // //cmdLine.AppendSwitch("disk-cache-size", "1");
                    // //if (!Environment.Is64BitProcess)
                    // //{
                    // //    //MessageBox.Show("设置内存");
                    // //    cmdLine.AppendArgument("max-old-space-size=1000");
                    // // }

                    cmdLine.AppendSwitch("ignore-certificate-errors");
                    cmdLine.AppendSwitch("disable-web-security");
                    cmdLine.AppendSwitch("unsafely-treat-insecure-origin-as-secure", Wnconfig.GetUrl());
                    //args.AppendSwitch("enable-media-stream");
                    cmdLine.AppendSwitch("enable-media-stream", "1");
                    cmdLine.AppendSwitch("enable-print-preview");
                    cmdLine.AppendSwitch("autoplay-policy", "no-user-gesture-required");

                    cmdLine.AppendSwitch("--disable-web-security", "1");          //关闭同源策略,允许跨域
                    cmdLine.AppendSwitch("--disable-site-isolation-trials", "1"); //关闭站点隔离策略,允许跨域
                    cmdLine.AppendSwitch("disable-web-security", "1");            //关闭同源策略,允许跨域
                    cmdLine.AppendSwitch("disable-site-isolation-trials", "1");   //关闭站点隔离策略,允许跨域
                });

                env.CustomCefSettings(settings =>
                {
                    //MessageBox.Show(settings.CachePath);
                    // Configure default Cef settings here.
                    //settings.WindowlessRenderingEnabled = true;
                    //settings.
                    //settings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36";
                });

                env.CustomDefaultBrowserSettings(cefSettings =>
                {
                    cefSettings.ApplicationCache = Xilium.CefGlue.CefState.Disabled;
                    //cefSettings.ApplicationCache= Xilium.CefGlue.CefState.Disabled;

                    //  cefSettings.WebSecurity = Xilium.CefGlue.CefState.Disabled;

                    // Configure default browser settings here.
                });
            },
                                            app =>
            {
#if DEBUG
                // Use this setting if your application running in DEBUG mode, it will allow user to open or clode DevTools by right-clicking mouse button and selecting menu items on context menu.
                //app.UseDebuggingMode();
#endif


                app.UseLocalFileResource("http", "demo.app.local", "asserts");
                app.RegisterJavaScriptExtension(() => new WinningBrowerWindowExtension());
                // Clear all cached files such as cookies, histories, localstorages, etc.
                if (args != null && args.Length > 0 && args[0] == "DeleteCache")
                {
                    //RunServiceProxy.InvokProxy();

                    app.ClearCacheFile();
                }
                Thread.Sleep(600);
                //var thisProcess = Process.GetCurrentProcess();
                //if (Process.GetProcessesByName(thisProcess.ProcessName).Length == 1)
                //{
                //    if (Process.GetProcessesByName(thisProcess.ProcessName)[0].Id != thisProcess.Id)
                //    {
                //        Process.GetProcessesByName(thisProcess.ProcessName)[0].Kill();
                //    }
                //}

                app.UseSingleInstance(() =>
                {
                    //MessageBox.Show("只能运行一个程序");

                    RunServiceProxy.SetWebAppFrmFront();
                    return;
                });

                // Set a main window class inherit Formium here to start appliation message loop.
                app.UseMainWindow(context =>
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);


                    ShortCutHelper.SetWinningBrowerShortcut(Wnconfig.GetShortName(), Application.ExecutablePath);


                    // context.MainForm = new Form();
                    //Xilium.CefGlue.CefRuntime.AddCrossOriginWhitelistEntry("*", "http", "*", true);
                    //mfrm= new MainForm();
                    TaskCompletionSource <object> source = new TaskCompletionSource <object>();
                    Thread thread = new Thread(() =>
                    {
                        try
                        {
                            RunServiceProxy.InvokProxy();
                            source.SetResult("启动成功");
                        }
                        catch (Exception ex)
                        {
                            source.SetException(ex);
                        }
                    });
                    //thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    AutoUpdate();
                    return(new MainForm());
                });
            })
            // Build the NanUI runtime
            .Build()
            // Run the main process
            .Run();
        }