void ShutdownAppWithFallback(int exitCode, Application app) { try { app.Dispatcher.Invoke(() => app.Shutdown(exitCode)); } catch (Exception) { _exitHandler.Exit(exitCode); } }
static void Main() { //the WPF application object will be the main UI loop System.Windows.Application wpfApplication = new System.Windows.Application { //otherwise the application will close when all WPF windows are closed ShutdownMode = ShutdownMode.OnExplicitShutdown }; SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext()); //set the WinForms properties //notice how you don't need to do anything else with the Windows Forms Application (except handle exceptions) System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); WpfProgramAddWinForms p = new WpfProgramAddWinForms(); p.ExitRequested += (sender, e) => { wpfApplication.Shutdown(); }; Task programStart = p.StartAsync(); HandleExceptions(programStart, wpfApplication); wpfApplication.Run(); }
public static void InitIcon(System.Windows.Application app, Icon icon) { Notify = new System.Windows.Forms.NotifyIcon { Icon = icon, Visible = true }; //Notify.Name = ""; var menu = new System.Windows.Forms.ContextMenu(); var closeItem = new System.Windows.Forms.MenuItem { Text = "Exit" }; closeItem.Click += (sender, arg) => { app.Shutdown(); }; var openChromeItem = new System.Windows.Forms.MenuItem { Text = "Open in Chrome" }; openChromeItem.Click += (sender, arg) => { Utilities.RunExecutable("Chrome", StorageHelper.AchiveValue("pageloading", "http://hellerz.github.io/hellerz/")); }; menu.MenuItems.Add(openChromeItem); menu.MenuItems.Add(closeItem); Notify.ContextMenu = menu; }
static void Main() { //The WinForms Application will be the main UI loop System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false); SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); //it's more awkward to have WinForms run the show; in certain cirumstances, if you don't change the WPF Application shutdown mode, //the application will be destroyed when that window is closed (because of the default "OnLastWindowClose") //then when you open a second WPF window...boom System.Windows.Application wpfApplication = new System.Windows.Application { //comment out this line to test, then click the button on the form to show another WPF window ShutdownMode = ShutdownMode.OnExplicitShutdown }; WinFormsProgramAddWpf p = new WinFormsProgramAddWpf(); p.ExitRequested += (sender, e) => { System.Windows.Forms.Application.ExitThread(); }; Task programStart = p.StartAsync(); HandleExceptions(programStart); System.Windows.Forms.Application.Run(); //now the wpf application can also shut down wpfApplication.Shutdown(); }
public void Cleanup() { app.Dispatcher.Invoke(() => { app.Shutdown(); app = null; }); }
public void Dispose() { app.Dispatcher.Invoke(new Action(() => { app.Shutdown(); if (wb != null) { wb.Dispose(); } })); }
private void OnTimer(object sender, EventArgs eventArgs) { if (_application.Windows.Count == 0 && System.Windows.Forms.Application.OpenForms.Count == 0) { if (_nothing > 2) { Logging.Write("Nothing shown! Existing…"); _timer.Stop(); _application.Shutdown(); } else { _nothing++; } } else { _nothing = 0; } }
private void Form1_Load(object sender, EventArgs e) { // initialize WPF Application object, this will initialize resources that are // required by the InRule WPF controls System.Windows.Application app = new System.Windows.Application(); // set the shutdown mode to explicit so it will stay alive for the life of the WinForm app.ShutdownMode = ShutdownMode.OnExplicitShutdown; // create a delegate to close the Application object when the winform closes Closed += delegate { app.Shutdown(); }; }
public void Exit(byte exitCode) { if (System.Windows.Forms.Application.MessageLoop) { Environment.ExitCode = exitCode; System.Windows.Forms.Application.Exit(); } else { _app.Dispatcher.Invoke(() => _app.Shutdown(exitCode)); } }
static void RunUnderApplication(Activity activity) { Application application = new System.Windows.Application() { ShutdownMode = ShutdownMode.OnExplicitShutdown }; application.Startup += delegate { WorkflowApplication wfApp = new WorkflowApplication(activity); wfApp.SynchronizationContext = SynchronizationContext.Current; wfApp.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { application.Shutdown(); }; wfApp.Run(); }; application.Run(); }
private static async void HandleExceptions(Task task, Application wpfApplication) { try { await Task.Yield(); //ensure this runs as a continuation await task; } catch (Exception ex) { //deal with exception, either with message box //or delegating to general exception handling logic you may have wired up //e.g. to app.DispatcherUnhandledException and AppDomain.UnhandledException MessageBox.Show(ex.ToString()); wpfApplication.Shutdown(); } }
public void TemplatedParent_Should_Be_Set_On_Template_Root() { Window target = new Window(); Application app = new Application(); bool passed = false; target.Loaded += (s, e) => { FrameworkElement templateRoot = VisualTreeHelper.GetChild(target, 0) as FrameworkElement; passed = templateRoot.TemplatedParent == target; app.Shutdown(); }; app.Run(target); Assert.IsTrue(passed); }
private static async void HandleExceptions(Task task, System.Windows.Application wpfApplication) { try { await Task.Yield(); //ensure this runs as a continuation await task; } catch (Exception ex) { //deal with exception, either with message box //or delegating to general exception handling logic you may have wired up //e.g. to Application.DispatcherUnhandledException and AppDomain.UnhandledException System.Windows.MessageBox.Show(ex.ToString()); wpfApplication.Shutdown(); } }
public void Show(string uriString) { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { var message = "Please set STAThreadAttribute on application entry point (Main method)"; Console.WriteLine(message); throw new InvalidOperationException(message); } _app = new Application(); _window = new Window(); var browser = new WebBrowser(); _window.Content = browser; browser.Loaded += (sender, eventArgs) => { browser.Navigate(uriString); SetForegroundWindow(new WindowInteropHelper(_window).Handle); }; browser.Navigating += (sender, eventArgs) => { if (this.Navigating != null) { this.Navigating(this, eventArgs); } }; browser.Navigated += (sender, eventArgs) => { if (this.Navigated != null) { this.Navigated(this, eventArgs); } }; _window.Closed += (sender, eventArgs) => _app.Shutdown(); _app.Run(_window); }
public static async Task ShowWindow(Version version, IInstallerFactory factory, string logPath) { var tcs = new TaskCompletionSource<object>(); var thread = new Thread(() => { try { var application = new Application(); var installerWindow = new MainWindow(factory, version, () => application.Dispatcher.Invoke(() => application.Shutdown()), logPath); application.Run(installerWindow); } finally { tcs.TrySetResult(new object()); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); await tcs.Task; }
public static void Halt(int code = 0) { ThisApplication.Shutdown(code); }
private void CheckForRunningMoni(Application app) { var myName = Process.GetCurrentProcess().ProcessName; var sameNameProcesses = Process.GetProcessesByName(myName); if (sameNameProcesses.Length > 1) { MessageBox.Show("MONI läuft schon. Mit zwei laufenden MONIs haste nur Ärger...Tschö", "Problem"); app.Shutdown(); } }
public override void ExitApplication() { application.Shutdown(); }
public void Dispose() { _currentApplication?.Shutdown(); _currentApplication = null; }
public void MenuExit(object sender, RoutedEventArgs args) { _app = Application.Current; _app.Shutdown(); }
public static void Main() { using (new Mutex(true, Id, out var isNewInstance)) { if (!isNewInstance) { return; } var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; app.DispatcherUnhandledException += (_, e) => { ShowFeedbackMessage(e.Exception); }; AppDomain.CurrentDomain.UnhandledException += (_, e) => { ShowFeedbackMessage(e.ExceptionObject); }; TaskScheduler.UnobservedTaskException += (_, e) => { ShowFeedbackMessage(e.Exception); }; void ShowFeedbackMessage(object exception) { MessageBox.Show("Battery Percentage Icon has run into an error. You can help to fix this by:\r\n" + "1. press Ctrl+C on this message\r\n" + "2. paste it in an email\r\n" + "3. send it to [email protected]\r\n\r\n" + (exception is Exception exp ? exp.ToString() : $"Error type: {exception.GetType().FullName}\r\n{exception}"), "You Found An Error"); } // Right click menu with "Exit" item to exit this application. using (var exitMenuItem = new ToolStripMenuItem("Exit")) using (var settingsMenuItem = new ToolStripMenuItem("Settings")) using (var detailsMenuItem = new ToolStripMenuItem("Battery Details")) using (var menu = new ContextMenuStrip { Items = { detailsMenuItem, settingsMenuItem, exitMenuItem } }) using (var notifyIcon = new NotifyIcon { Visible = true, ContextMenuStrip = menu }) { void ActivateDialog <T>() where T : Window, new() { var existingWindow = app.Windows.OfType <T>().FirstOrDefault(); if (existingWindow == null) { new T().Show(); } else { existingWindow.Activate(); } } exitMenuItem.Click += (_, __) => app.Shutdown(); settingsMenuItem.Click += (_, __) => ActivateDialog <SettingsWindow>(); detailsMenuItem.Click += (_, __) => ActivateDialog <DetailsWindow>(); // Setup variables used in the repetitively ran "Update" local function. (NotificationType Type, DateTime DateTime)lastNotification = (default, default);
/// <summary> /// Shuts down the application /// </summary> public void ShutDown() { m_wpfApplication.Shutdown(); }
public override void ExitApplication() { dispatcherTimer?.Stop(); application.Shutdown(); }
public static void TcpConnectionServer(Int32 port /*, IPAddress myIp*/) { TcpListener _server = null; try { // Set the TcpListener on port Int32 _port = port; IPAddress _myIp = IPAddress.Any;//myIp; //GetMyLocalIPv4(); // or IPAddress.Parse ("168.198.0.1") // TcpListener server = new TcpListener(port); _server = new TcpListener(_myIp, _port); // Start listening for client requests. _server.Start(); // Buffer for reading data Byte[] _bytes = new Byte[2000]; String _data = null; // Enter the listening loop. while (true) { Console.WriteLine("Waiting for connection..."); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient _client = _server.AcceptTcpClient(); Console.WriteLine("Connected!"); _data = null; // Get a stream object for reading and writing NetworkStream _stream = _client.GetStream(); int i; // Loop to receive all the data sent by the client. while ((i = _stream.Read(_bytes, 0, _bytes.Length)) != 0) { // Translate data bytes to a ASCII string. _data = System.Text.Encoding.ASCII.GetString(_bytes, 0, i); //Console.WriteLine($"Received: {_data}"); // Process the data sent by the client. //_data = _data.ToUpper(); //byte[] _msg = System.Text.Encoding.ASCII.GetBytes(_data); // Send back a response. //_stream.Write(_msg, 0, _msg.Length); Console.WriteLine($"Sent: {_data}"); } // Shutdown and end connection _client.Close(); } } catch (SocketException e) { System.Windows.MessageBox.Show($"SocketException: {e}"); } finally { // Stop listening for new clients. _server.Stop(); } MessageBoxResult result = System.Windows.MessageBox.Show("Do you want to close this window?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { //Total nn = new Total(result); System.Windows.Application myApp = new System.Windows.Application(); myApp.Shutdown(); } }// MSDN метод запуска TCP сервера, работает (необходима доработка).
/// <summary> /// Metodo que crea el notifyIcon, se pasa el form sobre el que se va aplicar. /// </summary> /// <param name="form">Formulario que se aplica al NotifyIcon</param> /// <returns>torna un objecto de tipo NotifyIcon</returns> /// <history> /// [michan] 25/04/2016 Created /// </history> public static NotifyIcon Notify(System.Windows.Application app = null, System.Windows.Window form = null, string title = null) { /// Objeto del tipo NotifyIcon System.Windows.Forms.NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon(); //_frm = form; ///icono que muestra la nube de notificación. será tipo info, pero existen warning, error, etc.. notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; string strTitle = ""; ///la ruta del icono que se va a mostrar cuando la app esté minimizada. if (form != null) { if (form.Icon != null) { Uri iconUri = new Uri(form.Icon.ToString(), UriKind.RelativeOrAbsolute); System.IO.Stream iconStream = System.Windows.Application.GetResourceStream(new Uri(form.Icon.ToString())).Stream; notifyIcon.Icon = new System.Drawing.Icon(iconStream); } strTitle = form.Title.ToString(); } // AppContext.BaseDirectory else if (app != null) { notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath); } if (title != null) { strTitle = title; } //notifyIcon.Icon = new System.Drawing.Icon(iconStream);//@"M:\PalaceResorts\Client4.6\IntelligenceMarketing\IM.Base\Images\IM.ico"); /// Mensaje que se muestra al minimizar al formulario notifyIcon.BalloonTipTitle = "Information"; notifyIcon.Text = (!String.IsNullOrEmpty(strTitle) && !String.IsNullOrWhiteSpace(strTitle)) ? strTitle : "The application"; notifyIcon.BalloonTipText = "Running " + strTitle; notifyIcon.Visible = true; /// Evento clic para mostrar la ventana cuando se encuentre minimizada. notifyIcon.Click += new EventHandler( (s, e) => { if (notifyIcon != null) { /// cuando se pulse el boton mostrará informacion, cambiaremos los textos para que muestre que la app esta trabajando... notifyIcon.BalloonTipIcon = ToolTipIcon.Warning; notifyIcon.BalloonTipText = strTitle + " is working..."; notifyIcon.BalloonTipTitle = "Wait..."; notifyIcon.ShowBalloonTip(400); notifyIcon.BalloonTipIcon = ToolTipIcon.Info; notifyIcon.BalloonTipText = strTitle + " Running..."; notifyIcon.BalloonTipTitle = "Information"; } } ); notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler( (s, e) => { if (notifyIcon != null) { if (form != null) { form.Show(); form.WindowState = WindowState.Normal; form.Activate(); } else if (app != null) { app.MainWindow.Show(); app.MainWindow.WindowState = WindowState.Normal; app.MainWindow.Activate(); } notifyIcon.Visible = true; notifyIcon.ContextMenu.MenuItems[0].Visible = false; notifyIcon.ContextMenu.MenuItems[1].Visible = true; } } ); // agrgegamos el menu en el notyficon notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu( /// Menu contextual que sera visible en el icono new System.Windows.Forms.MenuItem[] { new System.Windows.Forms.MenuItem( "Show",// opcion de abrir para cuando la ventana este minimizada (s, e) => { if (form != null) { //Se agrega al menu la opcion para mostrar el formulario form.Show(); form.WindowState = WindowState.Normal; form.Activate(); } else if (app != null) { app.MainWindow.Show(); app.MainWindow.WindowState = WindowState.Normal; app.MainWindow.Activate(); } notifyIcon.Visible = true; notifyIcon.ContextMenu.MenuItems[0].Visible = false; notifyIcon.ContextMenu.MenuItems[1].Visible = true; } ), new System.Windows.Forms.MenuItem( "Hide",// opcion para mostrar la ventana cuando se encuentre maximizada (s, e) => { if (form != null) { // Se agrega en el menu la opcion para ocultar el form form.Hide(); form.WindowState = WindowState.Minimized; } else if (app != null) { app.MainWindow.Hide(); app.MainWindow.WindowState = WindowState.Minimized; } notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(400); notifyIcon.ContextMenu.MenuItems[0].Visible = true; notifyIcon.ContextMenu.MenuItems[1].Visible = false; } ), new System.Windows.Forms.MenuItem("-"), new System.Windows.Forms.MenuItem("Close", (s, e) => { if (form != null) { form.Close(); } else if (app != null) { app.Shutdown(); } } ) } ); notifyIcon.ContextMenu.MenuItems[0].Visible = false; notifyIcon.ContextMenu.MenuItems[1].Visible = true; return(notifyIcon); }
public void menuExit(object sender, RoutedEventArgs args) { app = (Application)System.Windows.Application.Current; app.Shutdown(); }