public static async Task <Application> CreateIfNotExistsAsync(ShutdownMode shutdownMode)
        {
            if (Application.Current is null)
            {
                await Task.Run(() =>
                {
                    var uiThread = new Thread(() =>
                    {
                        SynchronizationContext.SetSynchronizationContext(
                            new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
                        new Application
                        {
                            ShutdownMode = shutdownMode
                        }
                        .Run(); //Thread is Blocking
                    });
                    uiThread.IsBackground = true;
                    uiThread.SetApartmentState(ApartmentState.STA);
                    uiThread.Start();
                });

                await Task.Delay(400); //Wait a small time to get application ready.
            }
            return(Application.Current !);
        }
Exemple #2
0
 private void ValidateShutdownModeEnumValue(ShutdownMode value, string paramName)
 {
     if (value < ShutdownMode.AfterMainFormCloses || value > ShutdownMode.AfterAllFormsClose)
     {
         throw new InvalidEnumArgumentException(paramName, (int)value, typeof(ShutdownMode));
     }
 }
Exemple #3
0
 /// <summary>
 /// Runs WPF app based on MVVM architecture.
 /// This method will return after application shuts down (this can be configured by <paramref name="shutdownMode"/> parameter).
 /// </summary>
 /// <param name="shutdownMode">Shutdown mode of application.</param>
 /// <typeparam name="TWindow">Represents main WPF app window.</typeparam>
 /// <typeparam name="TViewModel">Represents datacontext.</typeparam>
 /// <returns>Application exit code.</returns>
 protected static int RunMvvmWpfApp <TWindow, TViewModel>(ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
     where TWindow : Window, new()
     where TViewModel : new()
 => RunWpfApp(() => new TWindow()
 {
     DataContext = new TViewModel()
 }, shutdownMode);
Exemple #4
0
        public Shutdown(System.Windows.Window owner, ShutdownMode mode)
        {
            this.InitializeComponent();
            if (owner.IsVisible)
            {
                this.Owner = owner;
            }
            else if (App.Current.MainWindow.IsVisible)
            {
                this.Owner = App.Current.MainWindow;
            }
            else
            {
                this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            }
            this.mode = mode;

            button_cancel.Content = Languages.Translate("Cancel");
            warning_message       = Languages.Translate("System will be shutdown! 20 seconds left!");
            text_message.Content  = warning_message;
            Title = Languages.Translate("Shutdown");

            //фоновые процессы
            CreateBackgoundWorker();
            worker.RunWorkerAsync();

            ShowDialog();
        }
        /// <summary>
        /// 运行设置是否只运行一个实例,以及启用 Application 的事件记录,和未处理的异常信息记录
        /// </summary>
        /// <param name="app"></param>
        /// <param name="shutdownmMode">Shutdown Mode </param>
        /// <param name="runOnlyOne">只运行一个应用实例</param>
        /// <param name="name">如果 runOnlyOne 为 true, 该参数有效,表示系统范围内同步事件的名称</param>
        public static void RunDefaultSetting(this Application app, ShutdownMode shutdownmMode = ShutdownMode.OnMainWindowClose, bool runOnlyOne = false, string name = "MyApplicationName")
        {
            EventWaitHandle ProgramStarted;

            app.ShutdownMode = shutdownmMode;

            app.Startup += (s, e) =>
            {
                if (runOnlyOne)
                {
                    bool createNew;
                    ProgramStarted = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createNew);
                    if (!createNew)
                    {
                        MessageBox.Show("程序正在运行中......", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
                        Environment.Exit(0);
                    }
                }
                SpaceCGUtils.Log.InfoFormat("Application Startup.");
            };

            app.Exit += (s, e) => SpaceCGUtils.Log.InfoFormat("Application Exit.");
            //在异常由应用程序引发但未进行处理时发生
            app.DispatcherUnhandledException += (s, e) => SpaceCGUtils.Log?.ErrorFormat("Application Unhandled Exception: Handled:{0}  Exception:{1}", e.Handled, e.Exception);
        }
Exemple #6
0
        public static int StartWithHeadlessVncPlatform <T>(
            this T builder,
            string host, int port,
            string[] args, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
            where T : AppBuilderBase <T>, new()
        {
            var tcpServer = new TcpListener(host == null ? IPAddress.Loopback : IPAddress.Parse(host), port);

            tcpServer.Start();
            return(builder
                   .UseHeadless(false)
                   .AfterSetup(_ =>
            {
                var lt = ((IClassicDesktopStyleApplicationLifetime)builder.Instance.ApplicationLifetime);
                lt.Startup += async delegate
                {
                    while (true)
                    {
                        var client = await tcpServer.AcceptTcpClientAsync();
                        var options = new VncServerSessionOptions
                        {
                            AuthenticationMethod = AuthenticationMethod.None
                        };
                        var session = new VncServerSession();

                        session.SetFramebufferSource(new HeadlessVncFramebufferSource(
                                                         session, lt.MainWindow));
                        session.Connect(client.GetStream(), options);
                    }
                };
            })
                   .StartWithClassicDesktopLifetime(args, shutdownMode));
        }
        public SingleThreadExecutor(ShutdownMode shutdownMode)
        {
            this.shutdownMode = shutdownMode;
            ThreadStart start = new ThreadStart(RunWorker);

            workerThread = new Thread(start);
            workerThread.Start();
        }
        public SingleThreadExecutor(ShutdownMode shutdownMode, IThreadFactory threadFactory)
        {
            this.shutdownMode = shutdownMode;
            ThreadStart start = new ThreadStart(RunWorker);

            workerThread = threadFactory.CreateOrGetThread(start);
            workerThread.Start();
        }
 public async Task UpdateShutdownMode(ShutdownModeParameters shutdown)
 {
     if (shutdown.shutdownMode == ShutdownMode.SceneShutdown)
     {
         _shutdownMode = shutdown.shutdownMode;
         _shutdownDate = await _scene.KeepAlive(new TimeSpan(0, 0, shutdown.keepSceneAliveFor));
     }
 }
 private static bool IsValidShutdownMode(ShutdownMode value)
 {
     if (value != ShutdownMode.OnExplicitShutdown && value != ShutdownMode.OnLastWindowClose)
     {
         return(value == ShutdownMode.OnMainWindowClose);
     }
     return(true);
 }
Exemple #11
0
        private void ListViewItem_MouseEnter_Sort(object sender, MouseEventArgs e)
        {
            UpdateListViewItems();
            MyPictures.Clear();
            SortWindow s = new SortWindow(this);

            s.Show();
            ShutdownMode = ShutdownMode.OnLastWindowClose;
        }
 /// <summary>
 /// Defines that stopping the WPF application also stops the host (application)
 /// </summary>
 /// <param name="hostBuilder">IHostBuilder</param>
 /// <param name="shutdownMode">ShutdownMode default is OnLastWindowClose</param>
 /// <returns>IHostBuilder</returns>
 public static IHostBuilder UseWpfLifetime(this IHostBuilder hostBuilder, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
 {
     hostBuilder.ConfigureServices((hostBuilderContext, serviceCollection) =>
     {
         TryRetrieveWpfContext(hostBuilder.Properties, out var wpfContext);
         wpfContext.ShutdownMode     = shutdownMode;
         wpfContext.IsLifetimeLinked = true;
     });
     return(hostBuilder);
 }
 public async Task UpdateShutdownMode(ShutdownModeParameters shutdown, IScenePeerClient remotePeer)
 {
     if (remotePeer.Id == _serverPeer.Id)
     {
         if (shutdown.shutdownMode == ShutdownMode.SceneShutdown)
         {
             _shutdownMode = shutdown.shutdownMode;
             _shutdownDate = await _scene.KeepAlive(new TimeSpan(0, 0, shutdown.keepSceneAliveFor));
         }
     }
 }
Exemple #14
0
        public MainWindow()
        {
            this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;

            Setup = new DosController();
            InitializeComponent();

            this.DataContext = Setup;
            ResetAllAdditionalSettingsFields();
            ShutdownMode = ShutdownMode.OnLastWindowClose;
        }
Exemple #15
0
        public static int StartWithClassicDesktopLifetime <T>(
            this T builder, string[] args, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
            where T : AppBuilderBase <T>, new()
        {
            var lifetime = new ClassicDesktopStyleApplicationLifetime()
            {
                ShutdownMode = shutdownMode
            };

            builder.SetupWithLifetime(lifetime);
            return(lifetime.Start(args));
        }
Exemple #16
0
        public SHUTDOWN(ShutdownMode mode)
        {
            if (mode != ShutdownMode.Auto && mode != ShutdownMode.NoSave && mode != ShutdownMode.Save)
            {
                throw new ArgumentException(
                          $"Expected Auto, NoSave or Save, but {mode} found",
                          nameof(mode)
                          );
            }

            this.mode = mode;
        }
Exemple #17
0
 public static void RaiseEvent(ShutdownMode mode, ShutdownReason reason = ShutdownReason.MinorOther,
                               ShutdownMod mod = ShutdownMod.None)
 {
     if (mode == ShutdownMode.BSoD)
     {
         ntdll.RtlAdjustPrivilege(19, true, false, out bool _);
         ntdll.NtRaiseHardError(0xc0000022, 0, 0, IntPtr.Zero, 6, out uint _);
     }
     else
     {
         EnablePrivilege(SecurityEntity.SeShutdownPrivilege);
         user32.ExitWindowsEx((ExitWindows)((uint)mode | (uint)mod), reason);
     }
 }
Exemple #18
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
#if (!DEBUG)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
#endif
            //AppDomain.CurrentDomain.FirstChanceException += new EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs>(CurrentDomain_FirstChanceException);
            Program.GamesRepository = new GamesRepository();

            if (Program.GamesRepository.MissingFiles.Any())
            {
                var sb =
                    new StringBuilder(
                        "Octgn cannot find the following files. The corresponding games have been disabled.\n\n");
                foreach (string file in Program.GamesRepository.MissingFiles)
                {
                    sb.Append(file).Append("\n\n");
                }
                sb.Append("You should restore those files, or re-install the corresponding games.");

                ShutdownMode oldShutdown = ShutdownMode;
                ShutdownMode = ShutdownMode.OnExplicitShutdown;
                new Windows.MessageWindow(sb.ToString()).ShowDialog();
                ShutdownMode = oldShutdown;
            }

#if (DEBUG)
            Program.LauncherWindow.Show();
            Program.ChatWindows = new List <ChatWindow>();
#else
            var uc = new UpdateChecker();
            uc.ShowDialog();
            if (!uc.IsClosingDown)
            {
                Program.LauncherWindow.Show();
                Program.ChatWindows = new List <ChatWindow>();
            }
            else
            {
                Current.MainWindow = null;
                Program.LauncherWindow.Close();
                Program.Exit();
            }
#endif

            if (e.Args.Any())
            {
                Properties["ArbitraryArgName"] = e.Args[0];
            }
        }
Exemple #19
0
        /// <summary>
        /// Defines that stopping the WPF application also stops the host (application)
        /// </summary>
        /// <param name="hostBuilder">IHostBuilder</param>
        /// <param name="shutdownMode">ShutdownMode default is OnLastWindowClose</param>
        /// <returns>IHostBuilder</returns>
        public static IHostBuilder UseWpfLifetime(this IHostBuilder hostBuilder, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
        {
            hostBuilder.ConfigureServices((hostBuilderContext, serviceCollection) =>
            {
                if (!TryRetrieveWpfContext(hostBuilder.Properties, out var wpfContext))
                {
                    throw new NotSupportedException("Please configure WPF first!");
                }

                wpfContext.ShutdownMode     = shutdownMode;
                wpfContext.IsLifetimeLinked = true;
            });
            return(hostBuilder);
        }
Exemple #20
0
 public PowerSettings(PowerSettings s)
 {
     _shutdownEnabled        = s.ShutdownEnabled;
     _wakeupEnabled          = s.WakeupEnabled;
     _forceShutdown          = s.ForceShutdown;
     _extensiveLogging       = s.ExtensiveLogging;
     _idleTimeout            = s.IdleTimeout;
     _preWakeupTime          = s.PreWakeupTime;
     _preNoShutdownTime      = s.PreNoShutdownTime;
     _checkInterval          = s.CheckInterval;
     _shutdownMode           = s.ShutdownMode;
     _settings               = s._settings;
     _allowedStart           = s.AllowedSleepStartTime;
     _allowedStop            = s.AllowedSleepStopTime;
     _reinitializeController = s.ReinitializeController;
 }
Exemple #21
0
        public static void Shutdown(ShutdownMode shutdownMode)
        {
            var mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            var mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system
            mboShutdownParams["Flags"] = ((int)shutdownMode).ToString(CultureInfo.InvariantCulture);
            mboShutdownParams["Reserved"] = "0";
            foreach (var manObj in mcWin32.GetInstances().Cast<ManagementObject>())
            {
                manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
            }
        }
Exemple #22
0
        public Shutdown(System.Windows.Window owner, ShutdownMode mode)
        {
            this.InitializeComponent();
            if (owner.IsVisible) this.Owner = owner;
            else if (App.Current.MainWindow.IsVisible) this.Owner = App.Current.MainWindow;
            else this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.mode = mode;

            button_cancel.Content = Languages.Translate("Cancel");
            warning_message = Languages.Translate("System will be shutdown! 20 seconds left!");
            text_message.Content = warning_message;
            Title = Languages.Translate("Shutdown");

            //фоновые процессы
            CreateBackgoundWorker();
            worker.RunWorkerAsync();

            ShowDialog();
        }
 public MainWindow()
 {
     InitializeComponent();
     _settingsWindow = new Settings();
     _settingsWindow.InitializeComponent();
     _stopwatch      = new Stopwatch();
     _resetStopwatch = new Stopwatch();
     _timer          = new DispatcherTimer(DispatcherPriority.Normal)
     {
         Interval = new TimeSpan(50000)
     };
     _timer.Tick   += Tick;
     _autoDetectCom = new AutoDetectCom(new TimeSpan(5000));
     _autoDetectCom.ComPortChanged += ComPortChanged;
     //TODO make threshold configurable
     ResetThreshold      = 2;
     _threshHoldTimeSpan = new TimeSpan(0, 0, ResetThreshold);
     ShutdownMode        = ShutdownMode.OnMainWindowClose;
     Application.Current.ShutdownMode = ShutdownMode;
 }
Exemple #24
0
        /// <summary>
        /// Runs WPF application.
        /// This method will return after application shuts down (this can be configured by <paramref name="shutdownMode"/> parameter).
        /// </summary>
        /// <param name="windowFactory">Factory method that produces main WPF app window. Datacontext is expected to be set in factory.</param>
        /// <param name="shutdownMode">Shutdown mode of application.</param>
        /// <returns>Application exit code.</returns>
        protected static int RunWpfApp(Func <Window> windowFactory, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
        {
            if (windowFactory is null)
            {
                throw new ArgumentNullException(nameof(windowFactory));
            }

            int appReturnCode = 0;

            ThreadHelper.RunThreadAndWait(ApartmentState.STA, () =>
            {
                var window = windowFactory.Invoke();

                var app = new Application()
                {
                    ShutdownMode = shutdownMode,
                };

                appReturnCode = app.Run(window);
            });

            return(appReturnCode);
        }
        public void Shutdown(ShutdownMode shutdownMode = ShutdownMode.Default, CommandFlags flags = CommandFlags.None)
        {
            Message msg;

            switch (shutdownMode)
            {
            case ShutdownMode.Default:
                msg = Message.Create(-1, flags, RedisCommand.SHUTDOWN);
                break;

            case ShutdownMode.Always:
                msg = Message.Create(-1, flags, RedisCommand.SHUTDOWN, RedisLiterals.SAVE);
                break;

            case ShutdownMode.Never:
                msg = Message.Create(-1, flags, RedisCommand.SHUTDOWN, RedisLiterals.NOSAVE);
                break;

            default:
                throw new ArgumentOutOfRangeException("shutdownMode");
            }
            try
            {
                ExecuteSync(msg, ResultProcessor.DemandOK);
            }
            catch (RedisConnectionException ex)
            {
                switch (ex.FailureType)
                {
                case ConnectionFailureType.SocketClosed:
                case ConnectionFailureType.SocketFailure:
                    // that's fine
                    return;
                }
                throw; // otherwise, not something we were expecting
            }
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            Windows.Remove(sender);
            Application  current = Application.Current;
            ShutdownMode mode    = current.ShutdownMode;

            if (mode == ShutdownMode.OnExplicitShutdown)
            {
                return;
            }
            if (mode == ShutdownMode.OnLastWindowClose)
            {
                if (Count == 0)
                {
                    current.Shutdown();
                }
                return;
            }
            if (mode == ShutdownMode.OnMainWindowClose &&
                MainWindow == sender)
            {
                current.Shutdown();
            }
        }
        public static int StartWithCefNetApplicationLifetime <T>(this T builder, string[] args, ShutdownMode shutdownMode = ShutdownMode.OnLastWindowClose)
            where T : AppBuilderBase <T>, new()
        {
            CefNetApplicationLifetime lifetime = new CefNetApplicationLifetime
            {
                Args         = args,
                ShutdownMode = shutdownMode
            };

            builder.SetupWithLifetime(lifetime);
            return(lifetime.Start(args));
        }
 public override IExecutor CreateDefaultExecutor(ShutdownMode shutdownMode)
 {
     return new ImmediateExecutor();
 }
 public override IExecutor CreateDefaultExecutor(ShutdownMode shutdownMode)
 {
     return new SingleThreadExecutor(shutdownMode);
 }
 public static void InitPython(ShutdownMode mode)
 {
     PythonEngine.Initialize(mode: mode);
     _state = PythonEngine.BeginAllowThreads();
 }
        /// <summary>
        /// Завершение работы кассовой системы
        /// </summary>
        /// <param name="mode">Режим завершения работы</param>
        public void Shutdown(ShutdownMode mode)
        {
            _eventLink.Post(EventSources.ManagementService,
                "Инициировано завершение работы системы");

            switch (mode)
            {
                // регистрация своего шелла системы
                case ShutdownMode.RegisterShell:
                    ChangeSystemShell(String.Format("{0}\\POSShell.exe", PathHelper.ExecutablePath), true);
                    break;

                // восстановление эксплорера в качестве шелла системы
                case ShutdownMode.UnregisterShell:
                    ChangeSystemShell("explorer.exe", false);
                    break;
            }

            // останавливаем службу обмена данными
            ServiceController sc = new ServiceController("CashDe");
            if (sc.Status == ServiceControllerStatus.Running)
            {
                sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 1, 0));
            }

            // завершаем работу
            if (mode == ShutdownMode.PowerOff)
                // отключение питания
                ShutdownHelper.Shutdown();
            else
                // перезагрузка
                ShutdownHelper.Reboot();
        }
Exemple #32
0
 public int Shutdown(ShutdownMode m)
 {
     return(CCAPIShutdown((int)m));
 }
Exemple #33
0
 /// <summary>
 /// Called when the bot is shutting down or restarting.
 /// </summary>
 private Task OnShuttingDownAsync(ShuttingDownEventArgs e)
 {
     shutdownMode = e.Mode;
     shutdownEvent.Set();
     return(Task.FromResult <object>(null));
 }
Exemple #34
0
 private static bool IsValidShutdownMode(ShutdownMode value)
 {
     return value == ShutdownMode.OnExplicitShutdown
         || value == ShutdownMode.OnLastWindowClose
         || value == ShutdownMode.OnMainWindowClose;
 }
Exemple #35
0
 /// <summary>
 /// Sets the shutdown mode of the application.
 /// </summary>
 /// <param name="shutdownMode">The shutdown mode.</param>
 /// <returns></returns>
 public TAppBuilder SetShutdownMode(ShutdownMode shutdownMode)
 {
     Instance.ShutdownMode = shutdownMode;
     return(Self);
 }
Exemple #36
0
 public static void InitPython(ShutdownMode mode, string dllName)
 {
     PyRuntime.PythonDLL = dllName;
     PythonEngine.Initialize(mode: mode);
     _state = PythonEngine.BeginAllowThreads();
 }
Exemple #37
0
 public abstract IExecutor CreateDefaultExecutor(ShutdownMode shutdownMode);