我遇到了自定義wpf啓動屏幕實現的問題。 問題是加載完成後應顯示MainWindow,它有時不會被帶到前面,即Activate()調用失敗。它可能發生的1/10次。應用程序在Windows7/64上運行。在啓動屏幕關閉後將主窗口置於前面
這裏是implmentation(完整的源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);
}
}
我嘗試這樣做:
MainWindow = new Shell();
MainWindow.Topmost = true;
MainWindow.Show();
MainWindow.Activate();
MainWindow.Topmost = false;
,並似乎工作,感謝您的建議
在Windows XP上試了30次,我從未發現過這個問題。什麼操作系統你有這個問題? –
我也不能重現這個問題。我正在使用Windows 7. –
@Meleak Win7/64 – hkon