- Практическое руководство. Добавление в WPF-приложение экрана-заставки How to: Add a Splash Screen to a WPF Application
- Добавление существующего изображения в качестве экрана-заставки To add an existing image as a splash screen
- Исключение экрана-заставки из сборки To exclude the splash screen from build
- Удаление экрана-заставки из приложения To remove the splash screen from an application
- Screen Class
- Definition
- Examples
- Remarks
- Properties
- Methods
- Более продолжительное отображение экрана-заставки Display a splash screen for more time
- Добавление элемента Пустая страница в существующее приложение Add a Blank Page item to your existing app
- Базовый код XAML для расширенного экрана-заставки Essential XAML for an extended splash screen
- Базовый код для класса расширенного экрана-заставки Essential code for an extended splash screen class
- Измените обработчик события активации запуска Modify the launch activation handler
- Полный код Complete code
- Екстендедсплаш. XAML ExtendedSplash.xaml
- ExtendedSplash.xaml.cs ExtendedSplash.xaml.cs
- App.xaml.cs App.xaml.cs
- Связанные темы Related topics
Практическое руководство. Добавление в WPF-приложение экрана-заставки How to: Add a Splash Screen to a WPF Application
В этом разделе показано, как добавить окно запуска или экран-заставку в приложение Windows Presentation Foundation (WPF). This topic shows how to add a startup window, or splash screen, to a Windows Presentation Foundation (WPF) application.
Добавление существующего изображения в качестве экрана-заставки To add an existing image as a splash screen
Создайте или найдите изображение, которое вы хотите использовать для экрана-заставки. Create or find an image that you want to use for the splash screen. Можно использовать любой формат изображения, поддерживаемый компонентом Windows Imaging Component (WIC). You can use any image format that is supported by the Windows Imaging Component (WIC). Например, можно использовать формат BMP, GIF, JPEG, PNG или TIFF. For example, you can use the BMP, GIF, JPEG, PNG, or TIFF format.
Добавьте файл изображения в проект приложения WPF. Add the image file to the WPF Application project.
В Обозреватель решений выберите изображение. In Solution Explorer, select the image.
В окно свойств щелкните стрелку раскрывающегося списка для свойства действие сборки . In the Properties window, click the drop-down arrow for the Build Action property.
Выберите SplashScreen из раскрывающегося списка. Select SplashScreen from the drop-down list.
Нажмите клавишу F5 для сборки и запуска приложения. Press F5 to build and run the application.
Изображение экрана-заставки отображается в центре экрана, а затем исчезает при появлении главного окна приложения. The splash screen image appears in the center of the screen, and then fades when the main application window appears.
Исключение экрана-заставки из сборки To exclude the splash screen from build
В Обозреватель решений выберите изображение экрана-заставки. In Solution Explorer, select the splash screen image.
В окне Свойства задайте для действия сборки значение нет. In the Properties window, set the Build Action to None.
Удаление экрана-заставки из приложения To remove the splash screen from an application
В Обозреватель решений удалите изображение экрана-заставки. In Solution Explorer, delete the splash screen image.
Screen Class
Definition
Represents a display device or multiple display devices on a single system.
Examples
The following code example shows how to use various methods and properties of the Screen class. The example calls the AllScreens property to retrieve an array of all the screens connected to the system. For each returned Screen, the example adds the device name, bounds, type, working area, and primary screen to a ListBox. To use the example, add a ListBox and a Button to a form, and then add a Click event handler for the button.
Remarks
The constructor for this object is not public, so you cannot explicitly create a Screen object. The object is created when you call its public methods.
Properties
Gets an array of all displays on the system.
Gets the number of bits of memory, associated with one pixel of data.
Gets the bounds of the display.
Gets the device name associated with a display.
Gets a value indicating whether a particular display is the primary device.
Gets the primary display.
Gets the working area of the display. The working area is the desktop area of the display, excluding taskbars, docked windows, and docked tool bars.
Methods
Gets or sets a value indicating whether the specified object is equal to this Screen .
Retrieves a Screen for the display that contains the largest portion of the specified control.
Retrieves a Screen for the display that contains the largest portion of the object referred to by the specified handle.
Retrieves a Screen for the display that contains the specified point.
Retrieves a Screen for the display that contains the largest portion of the rectangle.
Retrieves the bounds of the display that contains the largest portion of the specified control.
Retrieves the bounds of the display that contains the specified point.
Retrieves the bounds of the display that contains the largest portion of the specified rectangle.
Computes and retrieves a hash code for an object.
Gets the Type of the current instance.
(Inherited from Object)
Retrieves the working area for the display that contains the largest region of the specified control. The working area is the desktop area of the display, excluding taskbars, docked windows, and docked tool bars.
Retrieves the working area closest to the specified point. The working area is the desktop area of the display, excluding taskbars, docked windows, and docked tool bars.
Retrieves the working area for the display that contains the largest portion of the specified rectangle. The working area is the desktop area of the display, excluding taskbars, docked windows, and docked tool bars.
Creates a shallow copy of the current Object.
(Inherited from Object)
Retrieves a string representing this object.
Более продолжительное отображение экрана-заставки Display a splash screen for more time
Важные API Important APIs
Увеличьте длительность отображения экрана-заставки, создав и использовав расширенный экран-заставку для приложения. Display a splash screen for more time by creating an extended splash screen for your app. Этот расширенный экран имитирует экран-заставку, отображаемый при запуске приложения, но его можно настраивать. This extended screen imitates the splash screen shown when your app is launched, but can be customized. Если вы хотите показывать информацию о загрузке в реальном времени или дать приложению дополнительное время на подготовку начального пользовательского интерфейса, расширенный экран-заставка позволит определить взаимодействие с пользователем при запуске. Whether you want to show real-time loading information or simply give your app extra time to prepare its initial UI, an extended splash screen lets you define the launch experience.
Фраза «Расширенный экран-заставка» в этом разделе относится к экрану-заставке, который остается на экране в течение продолжительного периода времени. The phrase «extended splash screen» in this topic refers to a splash screen that stays on the screen for an extended period of time. Он не представляет подкласс, производный от класса SplashScreen. It does not mean a subclass that derives from the SplashScreen class.
Убедитесь, что ваш расширенный экран-заставка точно имитирует экран-заставку, отображаемый по умолчанию. Для этого следуйте приведенным ниже рекомендациям. Make sure your extended splash screen accurately imitates the default splash screen by following these recommendations:
- Страница расширенного экрана-заставки должна использовать изображение размером 620 x 300 пикселей, соответствующее изображению, которое указано для экрана-заставки в манифесте приложения (изображение экрана-заставки вашего приложения). Your extended splash screen page should use a 620 x 300 pixel image that is consistent with the image specified for your splash screen in your app manifest (your app’s splash screen image). В Microsoft Visual Studio 2015 параметры экрана-заставки хранятся в разделе Экран-заставка на вкладке Визуальные активы в манифесте приложения (файл Package.appxmanifest). In Microsoft Visual Studio 2015, splash screen settings are stored in the Splash Screen section of the Visual Assets tab in your app manifest (Package.appxmanifest file).
- Расширенный экран-заставка должен использовать цвет фона, соответствующий цвету фона, который указан для экрана-заставки в манифесте приложения (фон экрана-заставки вашего приложения). Your extended splash screen should use a background color that is consistent with the background color specified for your splash screen in your app manifest (your app’s splash screen background).
- Чтобы расположить изображение расширенного экрана-заставки вашего приложения в тех экранных координатах, в которых располагается экран-заставка, отображаемый по умолчанию, в коде необходимо использовать класс SplashScreen. Your code should use the SplashScreen class to position your app’s splash screen image at the same screen coordinates as the default splash screen.
- Код должен реагировать на события изменения размера окна (например, при повороте экрана или при размещении вашего приложения рядом с другим приложением, открытым на экране), изменяя положение элементов на расширенном экране-заставке при помощи класса SplashScreen. Your code should respond to window resize events (such as when the screen is rotated or your app is moved next to another app onscreen) by using the SplashScreen class to reposition items on your extended splash screen.
Чтобы создать расширенный экран-заставку, имитирующий экран-заставку, который отображается по умолчанию, используйте процедуру, описанную ниже. Use the following steps to create an extended splash screen that effectively imitates the default splash screen.
Добавление элемента Пустая страница в существующее приложение Add a Blank Page item to your existing app
В этой статье подразумевается, что вы хотите добавить расширенный экран-заставку в существующий проект приложения универсальной платформы Windows (UWP) на C#, Visual Basic или C++. This topic assumes you want to add an extended splash screen to an existing Universal Windows Platform (UWP) app project using C#, Visual Basic, or C++.
- Откройте приложение в Visual Studio. Open your app in Visual Studio.
- Откройте пункт Проект в строке меню и нажмите кнопку Добавить новый элемент. Press or open Project from the menu bar and click Add New Item. Откроется диалоговое окно Добавление нового элемента. An Add New Item dialog box will appear.
- В этом диалоговом окне добавьте новую пустую страницу в приложение. From this dialog box, add a new Blank Page to your app. В этом разделе страница расширенного экрана-заставки называется ExtendedSplash. This topic names the extended splash screen page «ExtendedSplash».
При добавлении элемента пустая страница создаются два файла: один для разметки (ExtendedSplash.xaml) и второй для кода (ExtendedSplash.xaml.cs). Adding a Blank Page item generates two files, one for markup (ExtendedSplash.xaml) and another for code (ExtendedSplash.xaml.cs).
Базовый код XAML для расширенного экрана-заставки Essential XAML for an extended splash screen
Выполните эти действия, чтобы добавить изображение и элемент управления «Ход выполнения» на расширенный экран-заставку. Follow these steps to add an image and progress control to your extended splash screen.
В файле ExtendedSplash.xaml: In your ExtendedSplash.xaml file:
- Измените свойство Background элемента по умолчанию Grid в соответствии с цветом фона, настроенным для экрана-заставки вашего приложения в его манифесте (в разделе Визуальные активы файла Package.appxmanifest). Change the Background property of the default Grid element to match the background color you set for your app’s splash screen in your app manifest (in the Visual Assets section of your Package.appxmanifest file). Цвет экрана-заставки по умолчанию — светло-серый (шестнадцатеричное значение # 464646). The default splash screen color is a light gray (hex value #464646). Обратите внимание, что этот элемент Grid предоставляется по умолчанию при создании новой пустой страницы. Note that this Grid element is provided by default when you create a new Blank Page. Не нужно обязательно использовать Grid, — это просто удобная основа для создания расширенного экрана-заставки. You don’t have to use a Grid; it’s just a convenient base for building an extended splash screen.
- Добавьте элемент Canvas в Grid. Add a Canvas element to the Grid. Canvas используется для размещения изображения расширенного экрана-заставки. You’ll use this Canvas to position your extended splash screen image.
- Добавьте элемент Image в Canvas. Add an Image element to the Canvas. Используйте для расширенного экрана-заставки то же изображение размером 600 x 320 пикселей, которое вы выбрали для экрана-заставки, отображаемого по умолчанию. Use the same 600 x 320 pixel image for your extended splash screen that you chose for the default splash screen.
- (Необязательно) Добавьте элемент управления «Ход выполнения», который покажет пользователям, что ваше приложение загружается. (Optional) Add a progress control to show users that your app is loading. В этом разделе добавляется элемент ProgressRing вместо определенного или неопределенного элемента ProgressBar. This topic adds a ProgressRing, instead of a determinate or indeterminate ProgressBar.
В следующем примере демонстрируется Сетка с этими дополнениями и изменениями. The following example demonstrates a Grid with these additions and changes.
В этом примере для ширины прогрессринг устанавливается значение 20 пикселей. This example sets the width of the ProgressRing to 20 pixels. Можно вручную задать для ширины значение, подходящее для вашего приложения, но элемент управления не будет выполнять отрисовку при ширине меньше 20 пикселей. You can manually set its width to a value that works for your app, however, the control will not render at widths of less than 20 pixels.
Базовый код для класса расширенного экрана-заставки Essential code for an extended splash screen class
Расширенный экран-заставка должен реагировать на любые изменения размера (только Windows) или ориентации окна. Your extended splash screen needs to respond whenever the window size (Windows only) or orientation changes. Необходимо обновлять положение используемого изображения таким образом, чтобы расширенный экран-заставка смотрелся хорошо независимо от изменения размера окна. The position of the image you use must be updated so that your extended splash screen looks good no matter how the window changes.
Используйте эту процедуру, чтобы определить методы правильного отображения расширенного экрана-заставки. Use these steps to define methods to correctly display your extended splash screen.
Добавление обязательных пространств имен Add required namespaces
Необходимо добавить следующие пространства имен в ExtendedSplash.XAML.CS для доступа к классу SplashScreen , структуре Rect и событиям Window. SizeChanged . You’ll need to add the following namespaces to ExtendedSplash.xaml.cs to access the SplashScreen class, the Rect struct, and the Window.SizeChanged events.
Создайте разделяемый класс и объявите его переменные Create a partial class and declare class variables
Включите следующий код в файл ExtendedSplash.xaml.cs, чтобы создать разделяемый класс для представления расширенного экрана-заставки. Include the following code in ExtendedSplash.xaml.cs to create a partial class to represent an extended splash screen.
Эти переменные класса используются несколькими методами. These class variables are used by several methods. В переменной splashImageRect хранятся координаты, в которых система показывает изображение экрана-заставки для приложения. The splashImageRect variable stores the coordinates where the system displayed the splash screen image for the app. В переменной splash хранится объект SplashScreen, а переменная dismissed отслеживает, был ли закрыт экран-заставка, отображаемый системой. The splash variable stores a SplashScreen object, and the dismissed variable tracks whether or not the splash screen that is displayed by the system has been dismissed.
Определите конструктор для своего класса, который правильно размещает изображение Define a constructor for your class that correctly positions the image
Следующий код определяет конструктор для класса расширенного экрана-заставки, который ожидает передачи данных для событий изменения размера окна, размещает изображение и (необязательно) элемент управления «Ход выполнения» на расширенном экране-заставке, создает фрейм для навигации и вызывает асинхронный метод для восстановления сохраненного состояния сеанса. The following code defines a constructor for the extended splash screen class that listens for window resizing events, positions the image and (optional) progress control on the extended splash screen, creates a frame for navigation, and calls an asynchronous method to restore a saved session state.
Необходимо зарегистрировать обработчик Window.SizeChanged ( ExtendedSplash_OnResize в этом примере) в конструкторе класса, чтобы приложение правильно размещало изображение на расширенном экране-заставке. Make sure to register your Window.SizeChanged handler ( ExtendedSplash_OnResize in the example) in your class constructor so that your app positions the image correctly in your extended splash screen.
Определите метод класса, чтобы расположить изображение на расширенном экране-заставке Define a class method to position the image in your extended splash screen
Этот код демонстрирует размещение изображения на странице расширенного экрана-заставки с использованием переменной класса splashImageRect . This code demonstrates how to position the image on the extended splash screen page with the splashImageRect class variable.
(Необязательно) Определение метода класса, чтобы расположить элемент управления «Ход выполнения» на расширенном экране-заставке (Optional) Define a class method to position a progress control in your extended splash screen
Если вы решили добавить элемент ProgressRing на расширенный экран-заставку, определите его положение относительно изображения. If you chose to add a ProgressRing to your extended splash screen, position it relative to the splash screen image. Добавьте следующий код в файл ExtendedSplash.xaml.cs, чтобы расположить ProgressRing по центру на 32 пикселя ниже изображения. Add the following code to ExtendedSplash.xaml.cs to center the ProgressRing 32 pixels below the image.
Внутри класса определите обработчик события Dismissed Inside the class, define a handler for the Dismissed event
В файле ExtendedSplash.xaml.cs определите реакцию на событие SplashScreen.Dismissed, задав для переменной класса dismissed значение true. In ExtendedSplash.xaml.cs, respond when the SplashScreen.Dismissed event occurs by setting the dismissed class variable to true. Если ваше приложение предусматривает операции настройки, добавьте их в этот обработчик событий. If your app has setup operations, add them to this event handler.
По завершении настройки приложения перейдите с расширенного экрана-заставки на другую страницу. After app setup is complete, navigate away from your extended splash screen. Следующий код определяет метод DismissExtendedSplash для перехода на страницу MainPage , определенную в файле MainPage.xaml приложения. The following code defines a method called DismissExtendedSplash that navigates to the MainPage defined in your app’s MainPage.xaml file.
Внутри класса определите обработчик события Window.SizeChanged Inside the class, define a handler for Window.SizeChanged events
Подготовьте расширенный экран-заставку к изменению положения его элементов, если пользователь изменит размер окна. Prepare your extended splash screen to reposition its elements if a user resizes the window. Этот код определяет реакцию на событие Window.SizeChanged, фиксируя новые координаты и изменяя расположение изображения. This code responds when a Window.SizeChanged event occurs by capturing the new coordinates and repositioning the image. Если вы добавили на экран-заставку элемент управления «Ход выполнения», также измените его положение внутри этого обработчика событий. If you added a progress control to your extended splash screen, reposition it inside this event handler as well.
Прежде чем пытаться получить расположение образа, убедитесь, что переменная класса ( splash ) содержит допустимый объект SplashScreen , как показано в примере. Before you try to get the image location make sure the class variable ( splash ) contains a valid SplashScreen object, as shown in the example.
(Необязательно) Добавьте метода класса для восстановления сохраненного состояния сеанса (Optional) Add a class method to restore a saved session state
В результате выполнения кода, добавленного в метод OnLaunched в разделе «Шаг 4. Изменение обработчика события активации запуска», при запуске приложение отображает расширенный экран-заставку. The code you added to the OnLaunched method in Step 4: Modify the launch activation handler causes your app to display an extended splash screen when it launches. Чтобы консолидировать все методы, связанные с запуском приложения, в расширенном классе экрана-заставки, можно добавить метод в файл ExtendedSplash.xaml.cs для восстановления состояния приложения. To consolidate all methods related to app launch in your extended splash screen class, you could consider adding a method to your ExtendedSplash.xaml.cs file to restore the app’s state.
При изменении обработчика активации запуска в файле App.xaml.cs также задайте для loadstate значение true, если предыдущее состояние ApplicationExecutionState приложения было Terminated. When you modify the launch activation handler in App.xaml.cs, you’ll also set loadstate to true if the previous ApplicationExecutionState of your app was Terminated. В этом случае метод RestoreState восстанавливает предыдущее состояние приложения. If so, the RestoreState method restores the app to its previous state. Обзор запуска, приостановки и завершения приложения см. в статье Жизненный цикл приложения. For an overview of app launch, suspension, and termination, see App lifecycle.
Измените обработчик события активации запуска Modify the launch activation handler
При запуске приложения система передает информацию об экране-заставке обработчику событий активации запуска приложения. When your app is launched, the system passes splash screen information to the app’s launch activation event handler. Эту информацию можно использовать, чтобы правильно расположить изображение на странице расширенного экрана-заставки. You can use this information to correctly position the image on your extended splash screen page. Такую информацию об экране-заставке можно получить из аргументов события активации, которые передаются обработчику события OnLaunched приложения (см. переменную args в следующем коде). You can get this splash screen information from the activation event arguments that are passed to your app’s OnLaunched handler (see the args variable in the following code).
Если вы еще не переопределили обработчик OnLaunched для своего приложения, обратитесь к статье Жизненный цикл приложения, чтобы узнать, как обрабатывать события активации. If you have not already overridden the OnLaunched handler for your app, see App lifecycle to learn how to handle activation events.
Добавьте в файл App.xaml.cs следующий код для создания и отображения расширенного экрана-заставки. In App.xaml.cs, add the following code to create and display an extended splash screen.
Полный код Complete code
Следующий код немного отличается от фрагментов кода, показанных на предыдущих шагах. The following code slightly differs from the snippets shown in the previous steps.
- ExtendedSplash.xaml включает кнопку DismissSplash . ExtendedSplash.xaml includes a DismissSplash button. При нажатии этой кнопки обработчик событий DismissSplashButton_Click вызывает метод DismissExtendedSplash . When this button is clicked, an event handler, DismissSplashButton_Click , calls the DismissExtendedSplash method. В приложении вызовите DismissExtendedSplash , когда приложение закончит загрузку ресурсов или инициализацию пользовательского интерфейса. In your app, call DismissExtendedSplash when your app is done loading resources or initializing its UI.
- В этом приложении также используется шаблон приложения UWP с навигацией Frame. This app also uses a UWP app project template, which uses Frame navigation. В результате в файле App.xaml.cs обработчик активации запуска (OnLaunched) определяет элемент rootFrame и использует его для настройки содержимого окна приложения. As a result, in App.xaml.cs, the launch activation handler (OnLaunched) defines a rootFrame and uses it to set the content of the app window.
Екстендедсплаш. XAML ExtendedSplash.xaml
Этот пример включает DismissSplash кнопку, так как у нее нет ресурсов приложения для загрузки. This example includes a DismissSplash button because it doesn’t have app resources to load. В вашем приложении расширенный экран-заставка должен автоматически закрыться, когда приложение закончит загрузку ресурсов или подготовку начального пользовательского интерфейса. In your app, dismiss the extended splash screen automatically when your app is done loading resources or preparing its initial UI.
ExtendedSplash.xaml.cs ExtendedSplash.xaml.cs
Обратите внимание, что DismissExtendedSplash метод вызывается из обработчика событий Click для DismissSplash кнопки. Note that the DismissExtendedSplash method is called from the click event handler for the DismissSplash button. В вашем приложении кнопка DismissSplash не нужна. In your app, you won’t need a DismissSplash button. Вместо этого вызовите DismissExtendedSplash , когда приложение закончит загрузку ресурсов и вам потребуется перейти на его главную страницу. Instead, call DismissExtendedSplash when your app is done loading resources and you want to navigate to its main page.
App.xaml.cs App.xaml.cs
Этот проект был создан с помощью шаблона проекта приложения UWP Blank App (XAML) в Visual Studio. This project was created using the UWP app Blank App (XAML) project template in Visual Studio. Оба обработчика событий, OnNavigationFailed и OnSuspending , создаются автоматически, и их не нужно менять для реализации расширенного экрана-заставки. Both the OnNavigationFailed and OnSuspending event handlers are automatically generated and don’t need to be changed to implement an extended splash screen. В этом разделе меняется только OnLaunched . This topic only modifies OnLaunched .
Если вы не использовали шаблон проекта для своего приложения, посмотрите в разделе «Шаг 4. Изменение обработчика активации запуска» пример измененного обработчика OnLaunched , который не использует навигацию Frame. If you didn’t use a project template for your app, see Step 4: Modify the launch activation handler for an example of a modified OnLaunched that doesn’t use Frame navigation.
Связанные темы Related topics
Ссылки Reference