I have run into a problem with a custom wpf splash-screen implementation. The problem is that after the loading is finished and the MainWindow should be shown, it sometimes is not brought to front i.e Activate() call fails. It happens maybe 1/10 times. Application is run on Windows7/64.
Here is the implmentation (full source sample)
public partial class App : Application
{
private Splash _splash;
private SplashVM _viewModel;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// starts splash in separate GUI thread
StartSplash();
// continues on loading main application in main gui thread
LoadMainAppFakeSteps(1000, 3);
// tells splash screen to start shutting down
Stop();
// Creates mainwindow for application
// The problem is that the mainwindow sometimes fails to activate,
// even when user has not touched mouse or keyboard (i.e has not given any other programs or components focus)
MainWindow = new Shell();
MainWindow.Show();
MainWindow.Activate();
}
private void StartSplash()
{
_viewModel = new SplashVM();
var thread = new Thread(SplashThread);
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start(_viewModel);
}
private void SplashThread(object vm)
{
_splash = new Splash();
_splash.DataContext = vm;
_splash.Show();
System.Windows.Threading.Dispatcher.Run();
_splash = null;
_viewModel = null;
}
private void LoadMainAppFakeSteps(int stepDelayMs, int numSteps)
{
for (int i = 1; i <= numSteps; i++)
{
_viewModel.Text = i.ToString();
Thread.Sleep(stepDelayMs);
}
}
private void Stop()
{
if (_splash == null) throw new InvalidOperationException("Not showing splash screen");
_splash.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
}
}
I tried this:
MainWindow = new Shell();
MainWindow.Topmost = true;
MainWindow.Show();
MainWindow.Activate();
MainWindow.Topmost = false;
and it seems to work, thanks all your suggestions