1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
/* Dieses Snippet ist eines der 418 Rezepte des Buchs "Das C# 2010 Codebook" und wurde vom Autor mit freundlicher Genehmigung des Verlags veröffentlicht. */
/* Basis dieser Lösung ist, dass Sie in der App.xaml-Datei kein Startfenster angeben.
Das Startfenster wird, neben dem Splash-Fenster, von einem asynchron aufgerufenen
Delegaten in der überschriebenen OnStartup-Methode der Anwendung geöffnet. */
/* Der XAML-Code des Beispiel-Splash-Fensters */
<Window x:Class="..."
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="180" Width="280"
WindowStyle="None">
<Grid>
<TextBlock Name="txtInfo" Margin="10,10,0,28" TextWrapping="Wrap"
HorizontalAlignment="Left" Width="166">Info</TextBlock>
<ProgressBar Name="pbr" Height="20" VerticalAlignment="Bottom"/>
</Grid>
</Window>
/* Methode in der Klasse des Splash-Fensters */
public void SetInfo(string info, int progress)
{
this.txtInfo.Text = info;
this.pbr.Value = progress;
}
/* Die App-Klasse */
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Splash-Fenster öffnen
SplashWindow splashWindow = new SplashWindow();
splashWindow.Show();
// Delegat für die asynchrone Ausführung
// der Initialisierung
Action initializer = new Action(() =>
{
// Simulation einer Initialisierung
try
{
/* Initialisierung */
for (int i = 0; i < 100; i++)
{
// Das Splash-Fenster aktualisieren
splashWindow.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() =>
{
splashWindow.SetInfo("Lese Datensatz " + i + " ...", i);
}));
// Die eigentliche Initialisierung wird hier nur simuliert
System.Threading.Thread.Sleep(30);
}
/* Ende der Initialisierung */
}
catch (Exception ex)
{
MessageBox.Show("Fehler beim Initialisieren: " + ex.Message,
"Splash-Fenster", MessageBoxButton.OK, MessageBoxImage.Error);
this.Shutdown();
}
});
// Delegat für den Callback der asynchronen Ausführung
AsyncCallback splashCloser = new AsyncCallback((result) =>
{
// Das Hauptfenster erzeugen, der Anwendung zuweisen
// und öffnen
this.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() =>
{
MainWindow mainWindow = new MainWindow();
this.MainWindow = mainWindow;
mainWindow.Show();
}));
// Schließen des Splash-Fensters
splashWindow.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() =>
{
splashWindow.Close();
}));
});
// Asynchrones Starten der Initialisierung
initializer.BeginInvoke(splashCloser, null);
}
}
|