- Создание настраиваемого поля ввода Creating a Custom Input Box
- Создание настраиваемого графического поля ввода Create a custom, graphical input box
- Списки с множественным выбором Multiple-selection List Boxes
- Создание списков, допускающих множественный выбор Create list box controls that allow multiple selections
- Выбор элементов из списка Selecting Items from a List Box
- Создание элемента управления «Список» и выбор элементов Create a list box control, and select items from it
Создание настраиваемого поля ввода Creating a Custom Input Box
Создание сценария настраиваемого графического поля ввода с помощью функций создания форм Microsoft .NET Framework в Windows PowerShell 3.0 и более поздних версиях. Script a graphical custom input box by using Microsoft .NET Framework form-building features in Windows PowerShell 3.0 and later releases.
Создание настраиваемого графического поля ввода Create a custom, graphical input box
Скопируйте и вставьте следующий код в интегрированную среду сценариев Windows PowerShell, а затем сохраните файл как сценарий Windows PowerShell (PS1-файл). Copy and then paste the following into Windows PowerShell ISE, and then save it as a Windows PowerShell script (.ps1).
Сценарий начинается с загрузки двух классов .NET Framework: System.Drawing и System.Windows.Forms. The script begins by loading two .NET Framework classes: System.Drawing and System.Windows.Forms. Затем вы запускаете новый экземпляр класса .NET Framework System.Windows.Forms.Form, предоставляющий пустую форму или окно, в которые можно добавить элементы управления. You then start a new instance of the .NET Framework class System.Windows.Forms.Form; that provides a blank form or window to which you can start adding controls.
После создания экземпляра класса «Форма» назначьте значения для трех свойств этого класса. After you create an instance of the Form class, assign values to three properties of this class.
Text. Text. Это будет заголовком окна. This becomes the title of the window.
Size. Size. Это размер формы в пикселях. This is the size of the form, in pixels. Предыдущий сценарий создает форму шириной 300 пикселей и высотой 200 пикселей. The preceding script creates a form that’s 300 pixels wide by 200 pixels tall.
StartingPosition. StartingPosition. Для этого дополнительного свойства задается значение CenterScreen в предыдущем сценарии. This optional property is set to CenterScreen in the preceding script. Если это свойство не добавлено, Windows выберет расположение после открытия формы. If you don’t add this property, Windows selects a location when the form is opened. Если для StartingPosition задать значение CenterScreen, форма будет автоматически отображаться в центре экрана при загрузке. By setting the StartingPosition to CenterScreen, you’re automatically displaying the form in the middle of the screen each time it loads.
Далее создайте кнопку OК для формы. Next, create an OK button for your form. Укажите размер и поведение кнопки ОК. Specify the size and behavior of the OK button. В этом примере кнопка расположена на 120 пикселей ниже верхней границы формы и на 75 пикселей правее левой границы. In this example, the button position is 120 pixels from the form’s top edge, and 75 pixels from the left edge. Высота кнопки — 23 пикселя, а длина — 75 пикселей. The button height is 23 pixels, while the button length is 75 pixels. Сценарий использует предопределенные типы Windows Forms для определения поведения кнопок. The script uses predefined Windows Forms types to determine the button behaviors.
Аналогичным образом создайте кнопку Отмена. Similarly, you create a Cancel button. Кнопка Отмена расположена на 120 пикселей ниже верхней границы и на 150 пикселей правее левой границы окна. The Cancel button is 120 pixels from the top, but 150 pixels from the left edge of the window.
Далее введите текст метки в окне, который должны получить пользователи. Next, provide label text on your window that describes the information you want users to provide.
Добавьте элемент управления (в данном случае текстовое поле), который позволит пользователям указать сведения, описанные в тексте метки. Add the control (in this case, a text box) that lets users provide the information you’ve described in your label text. Помимо текстового поля существует много других элементов управления, которые можно применить. Их описание см. в статье Пространство имен System.Windows.Forms. There are many other controls you can apply besides text boxes; for more controls, see System.Windows.Forms Namespace.
Задайте для свойства Topmost значение $true, чтобы принудительно открыть окно поверх других диалоговых окон. Set the Topmost property to $true to force the window to open atop other open windows and dialog boxes.
Затем добавьте следующую строку кода, чтобы активировать форму и установить фокус на текстовое поле, которое вы создали. Next, add this line of code to activate the form, and set the focus to the text box that you created.
Добавьте следующую строку кода для отображения формы в Windows. Add the following line of code to display the form in Windows.
Наконец, код внутри блока If указывает Windows, что следует делать с формой после того, как пользователь выберет параметр из списка и нажмет кнопку ОК или клавишу ВВОД. Finally, the code inside the If block instructs Windows what to do with the form after users provide text in the text box, and then click the OK button or press the Enter key.
Списки с множественным выбором Multiple-selection List Boxes
Используйте Windows PowerShell 3.0 и более поздние версии для создания списка с множественным выбором в настраиваемой форме Windows Form. Use Windows PowerShell 3.0 and later releases to create a multiple-selection list box control in a custom Windows Form.
Создание списков, допускающих множественный выбор Create list box controls that allow multiple selections
Скопируйте и вставьте следующий код в интегрированную среду сценариев Windows PowerShell, а затем сохраните файл как сценарий Windows PowerShell (PS1-файл). Copy and then paste the following into Windows PowerShell ISE, and then save it as a Windows PowerShell script (.ps1).
Сценарий начинается с загрузки двух классов .NET Framework: System.Drawing и System.Windows.Forms. The script begins by loading two .NET Framework classes: System.Drawing and System.Windows.Forms. Затем вы запускаете новый экземпляр класса .NET Framework System.Windows.Forms.Form, предоставляющий пустую форму или окно, в которые можно добавить элементы управления. You then start a new instance of the .NET Framework class System.Windows.Forms.Form; that provides a blank form or window to which you can start adding controls.
После создания экземпляра класса «Форма» назначьте значения для трех свойств этого класса. After you create an instance of the Form class, assign values to three properties of this class.
Text. Text. Это будет заголовком окна. This becomes the title of the window.
Size. Size. Это размер формы в пикселях. This is the size of the form, in pixels. Предыдущий сценарий создает форму шириной 300 пикселей и высотой 200 пикселей. The preceding script creates a form that’s 300 pixels wide by 200 pixels tall.
StartingPosition. StartingPosition. Для этого дополнительного свойства задается значение CenterScreen в предыдущем сценарии. This optional property is set to CenterScreen in the preceding script. Если это свойство не добавлено, Windows выберет расположение после открытия формы. If you don’t add this property, Windows selects a location when the form is opened. Если для StartingPosition задать значение CenterScreen, форма будет автоматически отображаться в центре экрана при загрузке. By setting the StartingPosition to CenterScreen, you’re automatically displaying the form in the middle of the screen each time it loads.
Далее создайте кнопку OК для формы. Next, create an OK button for your form. Укажите размер и поведение кнопки ОК. Specify the size and behavior of the OK button. В этом примере кнопка расположена на 120 пикселей ниже верхней границы формы и на 75 пикселей правее левой границы. In this example, the button position is 120 pixels from the form’s top edge, and 75 pixels from the left edge. Высота кнопки — 23 пикселя, а длина — 75 пикселей. The button height is 23 pixels, while the button length is 75 pixels. Сценарий использует предопределенные типы Windows Forms для определения поведения кнопок. The script uses predefined Windows Forms types to determine the button behaviors.
Аналогичным образом создайте кнопку Отмена. Similarly, you create a Cancel button. Кнопка Отмена расположена на 120 пикселей ниже верхней границы и на 150 пикселей правее левой границы окна. The Cancel button is 120 pixels from the top, but 150 pixels from the left edge of the window.
Далее введите текст метки в окне, который должны получить пользователи. Next, provide label text on your window that describes the information you want users to provide.
Добавьте элемент управления (в данном случае список), который позволит пользователям указать сведения, описанные в тексте метки. Add the control (in this case, a list box) that lets users provide the information you’ve described in your label text. Помимо текстового поля существует много других элементов управления, которые можно применить. Их описание см. в статье Пространство имен System.Windows.Forms. There are many other controls you can apply besides text boxes; for more controls, see System.Windows.Forms Namespace.
Далее показано, как указать, что вы разрешаете пользователям выбрать несколько значений в списке. Here’s how you specify that you want to allow users to select multiple values from the list.
В следующем разделе необходимо указать значения списка, которые должны отображаться пользователям. In the next section, you specify the values you want the list box to display to users.
Укажите максимальную высоту элемента управления «список». Specify the maximum height of the list box control.
Добавьте список в форму и настройте его так, чтобы он открывался в Windows поверх других диалоговых окон. Add the list box control to your form, and instruct Windows to open the form atop other windows and dialog boxes when it’s opened.
Добавьте следующую строку кода для отображения формы в Windows. Add the following line of code to display the form in Windows.
Наконец, код внутри блока If указывает Windows, что следует делать с формой после того, как пользователь выберет параметр из списка и нажмет кнопку ОК или клавишу ВВОД. Finally, the code inside the If block instructs Windows what to do with the form after users select one or more options from the list box, and then click the OK button or press the Enter key.
Выбор элементов из списка Selecting Items from a List Box
Используйте Windows PowerShell 3.0 и более поздние версии для создания диалогового окна, в котором пользователи могут выбирать элементы из списка. Use Windows PowerShell 3.0 and later releases to create a dialog box that lets users select items from a list box control.
Создание элемента управления «Список» и выбор элементов Create a list box control, and select items from it
Скопируйте и вставьте следующий код в интегрированную среду сценариев Windows PowerShell, а затем сохраните файл как сценарий Windows PowerShell (PS1-файл). Copy and then paste the following into Windows PowerShell ISE, and then save it as a Windows PowerShell script (.ps1).
Сценарий начинается с загрузки двух классов .NET Framework: System.Drawing и System.Windows.Forms. The script begins by loading two .NET Framework classes: System.Drawing and System.Windows.Forms. Затем вы запускаете новый экземпляр класса .NET Framework System.Windows.Forms.Form, предоставляющий пустую форму или окно, в которые можно добавить элементы управления. You then start a new instance of the .NET Framework class System.Windows.Forms.Form; that provides a blank form or window to which you can start adding controls.
После создания экземпляра класса «Форма» назначьте значения для трех свойств этого класса. After you create an instance of the Form class, assign values to three properties of this class.
Text. Text. Это будет заголовком окна. This becomes the title of the window.
Size. Size. Это размер формы в пикселях. This is the size of the form, in pixels. Предыдущий сценарий создает форму шириной 300 пикселей и высотой 200 пикселей. The preceding script creates a form that’s 300 pixels wide by 200 pixels tall.
StartingPosition. StartingPosition. Для этого дополнительного свойства задается значение CenterScreen в предыдущем сценарии. This optional property is set to CenterScreen in the preceding script. Если это свойство не добавлено, Windows выберет расположение после открытия формы. If you don’t add this property, Windows selects a location when the form is opened. Если для StartingPosition задать значение CenterScreen, форма будет автоматически отображаться в центре экрана при загрузке. By setting the StartingPosition to CenterScreen, you’re automatically displaying the form in the middle of the screen each time it loads.
Далее создайте кнопку OК для формы. Next, create an OK button for your form. Укажите размер и поведение кнопки ОК. Specify the size and behavior of the OK button. В этом примере кнопка расположена на 120 пикселей ниже верхней границы формы и на 75 пикселей правее левой границы. In this example, the button position is 120 pixels from the form’s top edge, and 75 pixels from the left edge. Высота кнопки — 23 пикселя, а длина — 75 пикселей. The button height is 23 pixels, while the button length is 75 pixels. Сценарий использует предопределенные типы Windows Forms для определения поведения кнопок. The script uses predefined Windows Forms types to determine the button behaviors.
Аналогичным образом создайте кнопку Отмена. Similarly, you create a Cancel button. Кнопка Отмена расположена на 120 пикселей ниже верхней границы и на 150 пикселей правее левой границы окна. The Cancel button is 120 pixels from the top, but 150 pixels from the left edge of the window.
Далее введите текст метки в окне, который должны получить пользователи. Next, provide label text on your window that describes the information you want users to provide. В данном случае пользователям необходимо выбрать компьютер. In this case, you want users to select a computer.
Добавьте элемент управления (в данном случае список), который позволит пользователям указать сведения, описанные в тексте метки. Add the control (in this case, a list box) that lets users provide the information you’ve described in your label text. Помимо списка существует много других элементов управления, которые можно применить. Их описание см. в статье Пространство имен System.Windows.Forms. There are many other controls you can apply besides list boxes; for more controls, see System.Windows.Forms Namespace.
В следующем разделе необходимо указать значения списка, которые должны отображаться пользователям. In the next section, you specify the values you want the list box to display to users.
Список, созданный этим сценарием, позволяет выбрать только один вариант. The list box created by this script allows only one selection. Чтобы создать список, допускающий множественный выбор, укажите для свойства SelectionMode значение, аналогичное следующему: $listBox.SelectionMode = ‘MultiExtended’ . To create a list box control that allows multiple selections, specify a value for the SelectionMode property, similarly to the following: $listBox.SelectionMode = ‘MultiExtended’ . Дополнительные сведения см. в статье Списки с множественным выбором. For more information, see Multiple-selection List Boxes.
Добавьте список в форму и настройте его так, чтобы он открывался в Windows поверх других диалоговых окон. Add the list box control to your form, and instruct Windows to open the form atop other windows and dialog boxes when it’s opened.
Добавьте следующую строку кода для отображения формы в Windows. Add the following line of code to display the form in Windows.
Наконец, код внутри блока If указывает Windows, что следует делать с формой после того, как пользователь выберет параметр из списка и нажмет кнопку ОК или клавишу ВВОД. Finally, the code inside the If block instructs Windows what to do with the form after users select an option from the list box, and then click the OK button or press the Enter key.