【发布时间】:2011-11-10 11:17:34
【问题描述】:
我遇到了自定义 wpf 闪屏实现的问题。 问题是在加载完成并且应该显示 MainWindow 之后,它有时没有被带到前面,即 Activate() 调用失败。它可能发生 1/10 次。应用程序在 Windows7/64 上运行。
这是实现(完整源代码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。
-
为我工作没有问题,也有 Windows7、64 位..
-
+1 我有 exact 相同的问题(Windows 7 64 位)。在调试器下启动应用程序时不会发生这种情况,但在使用 F6 从 VS 中启动应用程序时会发生这种情况,有时也只是在资源管理器中运行 exe 时会发生这种情况
标签: wpf splash-screen