带ProgressBar的WPF SplashScreen

时间:2014-02-25 21:08:01

标签: wpf splash-screen

我有一个WPF项目,项目向导添加了一个启动画面。在同一个启动画面上,我想添加一个进度条样式表。有人知道怎么做吗?

3 个答案:

答案 0 :(得分:11)

这是我执行此操作的方案。我这样做的动机是我不想在UI线程上运行初始化代码,通常我想在我的App类(而不是Splash屏幕)上使用初始化代码。

基本上,我将应用StartupUri设置为我的启动画面,这样就可以实现滚动。

在启动画面上,我在应用程序上调用委托。这是在工作线程上运行的。在初始屏幕中,我处理EndInvoke,然后关闭窗口。

在应用程序初始化委托中,我完成工作,最后创建并打开正常的主窗口。在工作负载期间,我还有一个Slash方法,允许我更新进度。

好吧,代码相当短,并且不包含主窗口代码(不受所有这些影响),但是它与匿名代表一起躲避和潜水,所以仔细阅读,理想情况下在调试器。

这是代码......

<Application x:Class="SplashScreenDemo.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Splash.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>

应用程序代码背后......

internal delegate void Invoker();
public partial class App : Application
{
    public App()
    {
        ApplicationInitialize = _applicationInitialize;
    }
    public static new App Current
    {
        get { return Application.Current as App; }
    }
    internal delegate void ApplicationInitializeDelegate(Splash splashWindow);
    internal ApplicationInitializeDelegate ApplicationInitialize;
    private void _applicationInitialize(Splash splashWindow)
    {
        // fake workload, but with progress updates.
        Thread.Sleep(500);
        splashWindow.SetProgress(0.2);

        Thread.Sleep(500);
        splashWindow.SetProgress(0.4);

        Thread.Sleep(500);
        splashWindow.SetProgress(0.6);

        Thread.Sleep(500);
        splashWindow.SetProgress(0.8);

        Thread.Sleep(500);
        splashWindow.SetProgress(1);

        // Create the main window, but on the UI thread.
        Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Invoker)delegate
        {
            MainWindow = new Window1();
            MainWindow.Show();
        });           
    }
}

xaml(实际上,这里没什么太有意思的......)

<Window x:Class="SplashScreenDemo.Splash"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Splash" Height="300" Width="300">
    <Grid>
        <TextBlock Height="21" Margin="91,61,108,0" VerticalAlignment="Top">Splash Screen</TextBlock>
        <ProgressBar Name="progBar" Margin="22,122,16,109" Minimum="0" Maximum="1"/>
    </Grid>
</Window>

启动代码隐藏......

public partial class Splash : Window
{
    public Splash()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Splash_Loaded);
    }

    void Splash_Loaded(object sender, RoutedEventArgs e)
    {
        IAsyncResult result = null;

        // This is an anonymous delegate that will be called when the initialization has COMPLETED
        AsyncCallback initCompleted = delegate(IAsyncResult ar)
        {
            App.Current.ApplicationInitialize.EndInvoke(result);

            // Ensure we call close on the UI Thread.
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Invoker)delegate { Close(); });
        };

        // This starts the initialization process on the Application
        result = App.Current.ApplicationInitialize.BeginInvoke(this, initCompleted, null);
    }

    public void SetProgress(double progress)
    {
        // Ensure we update on the UI Thread.
        Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Invoker)delegate { progBar.Value = progress; });           
    }
}

当工作在工作线程上完成时,进度条将很好地更新,并且您在启动屏幕上的任何动画都将保持娱乐性。

答案 1 :(得分:0)

我使用了.NET Core,并且当有新线程Application.OnExit()被触发时。因此,我设法使其起作用的唯一方法是:

Application.cs:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    _mySplashScreenWindow.Show();


    var myTask = new Task(() =>
    {
        for (var i = 1; i <= 20; i++)
        {
            _mySplashScreenWindow.Dispatcher.Invoke(() =>
            {
                _mySplashScreenWindow.SomeTextBlock.Text = i.ToString();
                _mySplashScreenWindow.Progress = i; // or i / 20 for %
            });
            Thread.Sleep(250);
        }
    });

    myTask.ContinueWith(_ =>
    {
        MainWindow = null;

        var mainWindow = new MainWindow();
        // Or if you have access to the SplashScreen in the MainWindow, you can subscribe there
        mainWindow.Loaded += (sender, args) =>
        {
            _mySplashScreenWindow.Close();
            _mySplashScreenWindow = null;
        }

        MainWindow = mainWindow;
        mainWindow.ShowDialog();
    }, TaskScheduler.FromCurrentSynchronizationContext());

    myTask.Start();
}

答案 2 :(得分:0)

Ali 的答案不适用于 .NET 核心。但是,有一种解决方法,在我看来,它更直接。我相信它适用于所有“最新”版本的 .NET(可能是因为添加了 Task.Run)。

我使用了类似的方法,将另一个窗口用作启动画面。

我的 App.xaml 使用 Startup 事件而不是 StartupUri。不过,我相信这没有任何区别。

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

我没有为初始化声明新的委托类型。相反,我只是使用一种方法。 创建和显示主窗口可能需要一些时间,所以我认为最好只在窗口加载完成后返回,通过调整到它的 Loaded 事件。为此,我们使用 EventWaitHandle。

public partial class App : Application
{
    public App()
    {
    }
    
    public static new App Current { get => Application.Current as App; }

    private void OnStartup(object sender, StartupEventArgs e)
    {
        var splashScreen = new SplashScreenDemo.Splash();
        splashScreen.Show();
    }

    internal void InitializeApplication(Splash splashWindow)
    {
        // fake workload, but with progress updates.
        Thread.Sleep(500);
        splashWindow.SetProgress(0.25);

        Thread.Sleep(500);
        splashWindow.SetProgress(0.5);

        Thread.Sleep(500);
        splashWindow.SetProgress(0.75);

        EventWaitHandle mainWindowLoaded = new ManualResetEvent(false);

        // Create the main window, but on the UI thread.
        Dispatcher.BeginInvoke((Action)(() =>
        {
            MainWindow = new Window1();
            MainWindow.Loaded += (sender, e) =>
            {
                mainWindowLoaded.Set();
            };
            splashWindow.SetProgress(0.9);
            MainWindow.Show();
            splashWindow.SetProgress(1);
        }));
        
        // Wait until the Main window has finished initializing and loading
        mainWindowLoaded.WaitOne();        
    }
}

启动画面窗口可以使用一些窗口属性:

  • WindowStartupLocation="CenterScreen" 不言自明
  • WindowStyle="None" 以避免出现标题栏
  • ResizeMode="NoResize" 以防止用户移动或调整其大小
  • Topmost="True" 使其始终显示在其他窗口的顶部
<Window x:Class="SplashScreenDemo.Splash"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Splash" Height="300" Width="300" WindowStartupLocation="CenterScreen"
    WindowStyle="None" ResizeMode="NoResize" Topmost="True">
    <Grid>
        <TextBlock Height="21" VerticalAlignment="Top" TextAlignment="Center" Text="Loading"/>
        <ProgressBar Name="progBar" Margin="20,100" Minimum="0" Maximum="1"/>
    </Grid>
</Window>

启动画面的代码变得更容易理解,我们只需异步调用 init 方法。在某些应用程序中,我们还可以在关闭启动画面之前将焦点设置到主窗口。

public partial class Splash : Window
{
    public Splash()
    {
        InitializeComponent();
        this.Loaded += Splash_Loaded;
    }

    private async void Splash_Loaded(object sender, RoutedEventArgs e)
    {
        await Task.Run(() =>
        {
            App.Current.InitializeApplication(this);
            App.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                Close();
            }));
        });
    }

    public void SetProgress(double progress)
    {
        Dispatcher.BeginInvoke((Action)(() => progBar.Value = progress));           
    }
}