2010-09-15 12 views
5

Quiero que la aplicación WPF se inicie solo en ciertas condiciones. He intentado lo siguiente sin éxito:¿Cómo evitar que se cargue una aplicación WPF?

public partial class App : Application 
{ 
    protected override void OnStartup(StartupEventArgs e) 
    { 
     if (ConditionIsMet) // pseudo-code 
     { 
      base.OnStartup(e); 
     } 
    } 
} 

embargo, la aplicación se ejecuta normalmente, incluso cuando no se cumple la condición

Respuesta

13

Prueba esto:

protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 
    if (MyCondition) 
    { 
     ShowSomeDialog("Hey, I Can't start because..."); 
     this.Shutdown(); 
    } 
} 
+2

La aplicación todavía está tratando de abrir la StartupUri Prueba esto - http. : //stackoverflow.com/a/6602102/2342414 – benshabatnoam

3

Otra solución

Diseñador

<Application x:Class="SingleInstanceWPF.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Startup="Application_Startup"> 
</Application> 

código detrás

public partial class App : Application 
{ 
    private void Application_Startup(object sender, StartupEventArgs e) 
    { 
     if (ConditionIsMet) 
     { 
      var window = new MainWindow(); 
      window.Show(); 
     } 
     else 
     { 
      this.Shutdown(); 
     } 
    } 
} 
0

Puede ser que estoy haciendo esto de la manera muy, muy difícil, pero he encontrado que la lucha con la invocación precedencia/fin en el arranque, asumiendo que todo es inútil. Realmente quería que cualquier excepción planteada durante el inicio de la aplicación INMEDIATAMENTE saltara al manejador de excepciones más externo, pero incluso cuando se creó, mi objeto MVVM Locator se creaba automáticamente una instancia porque está definido como un recurso a nivel de aplicación.

Eso significaba que el pollo llegó antes que el huevo pero después del mismo huevo ya se había roto !!!

Así que la solución era:

1) Retire MVVM Localizador de App.xaml.

2) Crear un evento Application_Startup

Añadir estas líneas en la parte superior:

#region Handlers For Unhandled Exceptions 
     // anything else to do on startup can go here and will fire after the base startup event of the application 
     // First make sure anything after this is handled 
     // Creates an instance of the class holding delegate methods that will handle unhandled exceptions. 
     CustomExceptionHandler eh = new CustomExceptionHandler(); 

     AppDomain.CurrentDomain.UnhandledException += 
      new UnhandledExceptionEventHandler(eh.OnAppDomainException); 
     // this ensures that any unhandled exceptions bubble up to a messagebox at least 
     Dispatcher.CurrentDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(eh.OnDispatcherUnhandledException); 

     #endregion Handlers For Unhandled Exceptions 

3) Lazo de inicio para el evento Application_Startup en App.xaml por ejemplo

Startup="Application_Startup" <<<< this name is arbitrary but conventional AFAICT 

4) En Applicaton_Startup, crear el ViewModelLocator así:

  Resources.Add("Locator", new ViewModelLocator()); 
      //You can use FindResource and an exception will be thrown straightaway as I recall 
      if (!(TryFindResource("Locator") == null)) 

       throw new ResourceReferenceKeyNotFoundException("ViewModelLocator could not be created", "Locator"); 

5) Luego, inmediatamente después de que se ha encontrado el recurso, abra el MainWindow, pero sólo si el localizador se crea correctamente la instancia

  Uri uri = new Uri("pack:Views/MainWindow.xaml", UriKind.RelativeOrAbsolute); 
      Application.Current.StartupUri = uri; 

Paso (4) lanzará una excepción inmediatamente si el constructor en el localizador de falla que pasa todo el tiempo para mí, REGRETTTABLY.

Luego, a excepción de la etapa 4 se maneja de la siguiente manera (este ejemplo se utiliza un RadMessageBox pero no dude en arreglar eso:

public void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 
    { 
     try 
     { 

       var result = this.ShowExceptionDialog(e.Exception); 

     } 
     catch 
     { 


      RadMessageBox.Show("Fatal Dispatcher Error - the application will now halt.", Properties.Resources.CaptionSysErrMsgDlg, 
       MessageBoxButton.OK, MessageBoxImage.Stop, true); 
     } 

     finally 
     { 

      e.Handled = true; 

      // TERMINATE WITH AN ERROR CODE -1! 
      //Environment.Exit(-1); 
     } 
    } 
Cuestiones relacionadas