Dialog box windows form

Как создать диалоговое окно (C++) How to: Create a Dialog Box (C++)

Расположение и размер диалогового окна C++, а также расположение и размер элементов управления в нем измеряются в единицах диалогового окна. The location and size of a C++ dialog box, and the location and size of controls within it, are measured in dialog units. Значения для отдельных элементов управления и диалогового окна отображаются в правом нижнем углу строки состояния Visual Studio при их выборе. The values for individual controls and the dialog box appear in the lower right of the Visual Studio status bar when you select them.

Если в проекте еще нет RC-файла, см. раздел Создание нового файла описания ресурсов. If your project doesn’t already contain an .rc file, see Creating a New Resource Script File.

Инструкции How To

Редактор диалоговых окон позволяет: The Dialog Editor enables you:

Создание нового диалогового окна To create a new dialog box

В представление ресурсовщелкните правой кнопкой мыши RC -файл и выберите Добавить ресурс. In Resource View, right-click your .rc file and select Add Resource.

В диалоговом окне Добавление ресурса в списке тип ресурса выберите диалоговое окно , а затем нажмите кнопку создать. In the Add Resource dialog box, select Dialog in the Resource Type list, then choose New.

Если + рядом с типом ресурса диалогового окна отображается знак «плюс» (), это означает, что доступны шаблоны диалоговых окон. If a plus sign (+) appears next to the Dialog resource type, it means that dialog box templates are available. Щелкните знак «плюс», чтобы развернуть список шаблонов, выберите шаблон и нажмите кнопку создать. Select the plus sign to expand the list of templates, select a template, and choose New.

В редакторе диалоговых окон откроется диалоговое окно создать. The new dialog box opens in the Dialog Editor.

Также можно открыть существующие диалоговые окна в редакторе диалоговых окон для редактирования. You can also open existing dialog boxes in the Dialog Box editor for editing.

Создание диалогового окна, которое пользователь не может выйти To create a dialog box that a user can’t exit

Можно создать диалоговое окно среды выполнения, которое пользователь не может закрыть. You can create a runtime dialog box that a user can’t exit. Такой тип диалогового окна используется для входа в систему, блокирования приложений или документов. This kind of dialog box is useful for logons, and for application or document locks.

В области Свойства диалогового окна задайте для свойства системного меню значение false . In the Properties pane for the dialog box, set the System Menu property to false .

Этот параметр отключает системное меню диалогового окна и кнопку Закрыть . This setting disables the dialog box system menu and Close button.

В форме диалогового окна удалите кнопки Отмена и ОК . In the dialog box form, delete the Cancel and OK buttons.

Во время выполнения пользователь не может закрыть модальное диалоговое окно с такими характеристиками. At run time, a user can’t exit a modal dialog box that has these characteristics.

Чтобы включить тестирование этого типа диалогового окна, функция тестового диалогового окна обнаруживает, что нажата клавиша ESC . To enable testing of this kind of dialog box, the test dialog box function detects when Esc is pressed. Клавиша ESC также называется виртуальным ключом VK_ESCAPE. Esc is also known as the VK_ESCAPE virtual key. Независимо от того, как будет работать диалоговое окно во время выполнения, можно завершить тестовый режим, нажав клавишу ESC. No matter how the dialog box is designed to behave at run time, you can end test mode by pressing Esc.

Для создания диалогового окна, которое пользователи не могут выйти из приложения MFC, необходимо переопределить поведение по умолчанию OnOK и, OnCancel так как даже если удалить связанные кнопки, диалоговое окно по-прежнему может быть закрыто нажатием клавиши Ввод или ESC. For MFC applications, to create a dialog box that users cannot exit, you must override the default behavior of OnOK and OnCancel because even if you delete the associated buttons, the dialog box can still be dismissed by pressing Enter or Esc.

Указание расположения и размера диалогового окна To specify the location and size of a dialog box

В окне Свойства можно задать свойства, чтобы указать, где будет отображаться диалоговое окно на экране. There are properties you can set in the Properties Window to specify where a dialog box will appear onscreen.

Логическое свойство центра . The Boolean Center property.

Если задать значение true, диалоговое окно всегда будет отображаться в центре экрана. If you set the value to True, the dialog box will always appear in the center of the screen. Если для этого свойства задано значение false, можно задать свойства кспос и ИПОС . If you set this property to False, you can then set the XPos and YPos properties.

Свойства кспос и ИПОС , которые используются для явного определения того, где появится диалоговое окно. The XPos and YPos properties that are used to explicitly define where onscreen the dialog box will appear.

Эти свойства позиции являются значениями смещения в верхнем левом углу области просмотра, которая определена как . These position properties are offset values from the upper left-hand corner of the viewing area, which is defined as .

Читайте также:  Hp proliant dl380 g10 установка windows server 2019

Свойство абсолютного соответствия, которое влияет на положение. The Absolute Align property that affects position.

Если значение равно true, координаты задаются относительно экрана. If True, the coordinates are relative to the screen. Если значение равно false, координаты задаются относительно окна владельца диалогового окна. If False, the coordinates are relative to the dialog owner’s window.

Проверка диалогового окна To test a dialog box

При разработке диалогового окна можно смоделировать и протестировать его поведение во время выполнения, не компилируя программу. When you’re designing a dialog box, you can simulate and test its run-time behavior without compiling your program. В этом режиме можно выполнять следующие действия: In this mode, you can:

вводить текст, выбирать пункты в полях со списками, включать и отключать параметры, выбирать команды; Type text, select from combo-box lists, turn options on or off, and choose commands.

тестировать последовательность табуляции; Test the tab order.

проверять группировку элементов управления, например переключателей и флажков; Test the grouping of controls such as radio buttons and check boxes.

тестировать сочетания клавиш, используемые для доступа к элементам управления в диалоговом окне. Test the keyboard shortcuts for controls in the dialog box.

Подключения к коду диалогового окна, созданному с помощью мастеров, не включаются в имитацию. Connections to dialog box code made by using wizards aren’t included in the simulation.

При тестировании диалогового окна его положение обычно определяется относительно главного окна программы. When you test a dialog box, it typically displays at a location that’s relative to the main program window. Если для свойства абсолютное отображение диалогового окна задано значение true, то в диалоговом окне отображается положение относительно левого верхнего угла экрана. If you’ve set the dialog box Absolute Align property to True, the dialog box displays at a position that’s relative to the upper-left corner of the screen.

Когда Редактор диалоговых окон является активным окном, перейдите в > диалоговое окно Проверка формата меню. When the Dialog Editor is the active window, go to menu Format > Test Dialog.

Чтобы завершить моделирование, нажмите клавишу ESC или нажмите кнопку Закрыть в тестируемом диалоговом окне. To end the simulation, press Esc or select the Close button in the dialog box you’re testing.

Dialog boxes overview

Standalone applications typically have a main window that both displays the main data over which the application operates and exposes the functionality to process that data through user interface (UI) mechanisms like menu bars, tool bars, and status bars. A non-trivial application may also display additional windows to do the following:

Display specific information to users.

Gather information from users.

Both display and gather information.

These types of windows are known as dialog boxes, and there are two types: modal and modeless.

A modal dialog box is displayed by a function when the function needs additional data from a user to continue. Because the function depends on the modal dialog box to gather data, the modal dialog box also prevents a user from activating other windows in the application while it remains open. In most cases, a modal dialog box allows a user to signal when they have finished with the modal dialog box by pressing either an OK or Cancel button. Pressing the OK button indicates that a user has entered data and wants the function to continue processing with that data. Pressing the Cancel button indicates that a user wants to stop the function from executing altogether. The most common examples of modal dialog boxes are shown to open, save, and print data.

A modeless dialog box, on the other hand, does not prevent a user from activating other windows while it is open. For example, if a user wants to find occurrences of a particular word in a document, a main window will often open a dialog box to ask a user what word they are looking for. Since finding a word doesn’t prevent a user from editing the document, however, the dialog box doesn’t need to be modal. A modeless dialog box at least provides a Close button to close the dialog box, and may provide additional buttons to execute specific functions, such as a Find Next button to find the next word that matches the find criteria of a word search.

Windows Presentation Foundation (WPF) allows you to create several types of dialog boxes, including message boxes, common dialog boxes, and custom dialog boxes. This topic discusses each, and the Dialog Box Sample provides matching examples.

Message boxes

A message box is a dialog box that can be used to display textual information and to allow users to make decisions with buttons. The following figure shows a message box that displays textual information, asks a question, and provides the user with three buttons to answer the question.

To create a message box, you use the MessageBox class. MessageBox lets you configure the message box text, title, icon, and buttons, using code like the following.

To show a message box, you call the static Show method, as demonstrated in the following code.

When code that shows a message box needs to detect and process the user’s decision (which button was pressed), the code can inspect the message box result, as shown in the following code.

For more information on using message boxes, see MessageBox, MessageBox Sample, and Dialog Box Sample.

Although MessageBox may offer a simple dialog box user experience, the advantage of using MessageBox is that is the only type of window that can be shown by applications that run within a partial trust security sandbox (see Security), such as XAML browser applications (XBAPs).

Most dialog boxes display and gather more complex data than the result of a message box, including text, selection (check boxes), mutually exclusive selection (radio buttons), and list selection (list boxes, combo boxes, drop-down list boxes). For these, Windows Presentation Foundation (WPF) provides several common dialog boxes and allows you to create your own dialog boxes, although the use of either is limited to applications running with full trust.

Читайте также:  Формат msi mac os

Common dialog boxes

Windows implements a variety of reusable dialog boxes that are common to all applications, including dialog boxes for opening files, saving files, and printing. Since these dialog boxes are implemented by the operating system, they can be shared among all the applications that run on the operating system, which helps user experience consistency; when users are familiar with the use of an operating system-provided dialog box in one application, they don’t need to learn how to use that dialog box in other applications. Because these dialog boxes are available to all applications and because they help provide a consistent user experience, they are known as common dialog boxes.

Windows Presentation Foundation (WPF) encapsulates the open file, save file, and print common dialog boxes and exposes them as managed classes for you to use in standalone applications. This topic provides a brief overview of each.

Open File dialog

The open file dialog box, shown in the following figure, is used by file opening functionality to retrieve the name of a file to open.

The common open file dialog box is implemented as the OpenFileDialog class and is located in the Microsoft.Win32 namespace. The following code shows how to create, configure, and show one, and how to process the result.

For more information on the open file dialog box, see Microsoft.Win32.OpenFileDialog.

OpenFileDialog can be used to safely retrieve file names by applications running with partial trust (see Security).

Save File dialog box

The save file dialog box, shown in the following figure, is used by file saving functionality to retrieve the name of a file to save.

The common save file dialog box is implemented as the SaveFileDialog class, and is located in the Microsoft.Win32 namespace. The following code shows how to create, configure, and show one, and how to process the result.

For more information on the save file dialog box, see Microsoft.Win32.SaveFileDialog.

The print dialog box, shown in the following figure, is used by printing functionality to choose and configure the printer that a user would like to print data to.

The common print dialog box is implemented as the PrintDialog class, and is located in the System.Windows.Controls namespace. The following code shows how to create, configure, and show one.

For more information on the print dialog box, see System.Windows.Controls.PrintDialog. For detailed discussion of printing in WPF, see Printing Overview.

Custom dialog boxes

While common dialog boxes are useful, and should be used when possible, they do not support the requirements of domain-specific dialog boxes. In these cases, you need to create your own dialog boxes. As we’ll see, a dialog box is a window with special behaviors. Window implements those behaviors and, consequently, you use Window to create custom modal and modeless dialog boxes.

Creating a modal custom dialog box

This topic shows how to use Window to create a typical modal dialog box implementation, using the Margins dialog box as an example (see Dialog Box Sample). The Margins dialog box is shown in the following figure.

Configuring a modal dialog box

The user interface for a typical dialog box includes the following:

The various controls that are required to gather the desired data.

An OK button that users click to close the dialog box, return to the function, and continue processing.

A Cancel button that users click to close the dialog box and stop the function from further processing.

A Close button in the title bar.

Minimize, Maximize, and Restore buttons.

A System menu to minimize, maximize, restore, and close the dialog box.

A position above and in the center of the window that opened the dialog box.

The ability to be resized where possible to prevent the dialog box from being too small, and to provide the user with a useful default size. This requires that you set both the default and a minimum dimensions.

The ESC key as a keyboard shortcut that causes the Cancel button to be pressed. You do this by setting the IsCancel property of the Cancel button to true .

The ENTER (or RETURN) key as a keyboard shortcut that causes the OK button to be pressed. You do this by setting the IsDefault property of the OK button true .

The following code demonstrates this configuration.

The user experience for a dialog box also extends into the menu bar of the window that opens the dialog box. When a menu item runs a function that requires user interaction through a dialog box before the function can continue, the menu item for the function will have an ellipsis in its header, as shown here.

When a menu item runs a function that displays a dialog box which does not require user interaction, such as an About dialog box, an ellipsis is not required.

Opening a modal dialog box

A dialog box is typically shown as a result of a user selecting a menu item to perform a domain-specific function, such as setting the margins of a document in a word processor. Showing a window as a dialog box is similar to showing a normal window, although it requires additional dialog box-specific configuration. The entire process of instantiating, configuring, and opening a dialog box is shown in the following code.

Here, the code passes default information (the current margins) to the dialog box. It also sets the Window.Owner property with a reference to the window that is showing the dialog box. In general, you should always set the owner for a dialog box to provide window state-related behaviors that are common to all dialog boxes (see WPF Windows Overview for more information).

You must provide an owner to support user interface (UI) automation for dialog boxes (see UI Automation Overview).

After the dialog box is configured, it is shown modally by calling the ShowDialog method.

Validating user-provided data

When a dialog box is opened and the user provides the required data, a dialog box is responsible for ensuring that the provided data is valid for the following reasons:

Читайте также:  Программное обеспечение windows производитель

From a security perspective, all input should be validated.

From a domain-specific perspective, data validation prevents erroneous data from being processed by the code, which could potentially throw exceptions.

From a user-experience perspective, a dialog box can help users by showing them which data they have entered is invalid.

From a performance perspective, data validation in a multi-tier application can reduce the number of round trips between the client and the application tiers, particularly when the application is composed of Web services or server-based databases.

To validate a bound control in WPF, you need to define a validation rule and associate it with the binding. A validation rule is a custom class that derives from ValidationRule. The following example shows a validation rule, MarginValidationRule , which checks that a bound value is a Double and is within a specified range.

In this code, the validation logic of a validation rule is implemented by overriding the Validate method, which validates the data and returns an appropriate ValidationResult.

To associate the validation rule with the bound control, you use the following markup.

Once the validation rule is associated, WPF will automatically apply it when data is entered into the bound control. When a control contains invalid data, WPF will display a red border around the invalid control, as shown in the following figure.

WPF does not restrict a user to the invalid control until they have entered valid data. This is good behavior for a dialog box; a user should be able to freely navigate the controls in a dialog box whether or not data is valid. However, this means a user can enter invalid data and press the OK button. For this reason, your code also needs to validate all controls in a dialog box when the OK button is pressed by handling the Click event.

This code enumerates all dependency objects on a window and, if any are invalid (as returned by GetHasError, the invalid control gets the focus, the IsValid method returns false , and the window is considered invalid.

Once a dialog box is valid, it can safely close and return. As part of the return process, it needs to return a result to the calling function.

Setting the modal dialog result

Opening a dialog box using ShowDialog is fundamentally like calling a method: the code that opened the dialog box using ShowDialog waits until ShowDialog returns. When ShowDialog returns, the code that called it needs to decide whether to continue processing or stop processing, based on whether the user pressed the OK button or the Cancel button. To facilitate this decision, the dialog box needs to return the user’s choice as a Boolean value that is returned from the ShowDialog method.

When the OK button is clicked, ShowDialog should return true . This is achieved by setting the DialogResult property of the dialog box when the OK button is clicked.

Note that setting the DialogResult property also causes the window to close automatically, which alleviates the need to explicitly call Close.

When the Cancel button is clicked, ShowDialog should return false , which also requires setting the DialogResult property.

When a button’s IsCancel property is set to true and the user presses either the Cancel button or the ESC key, DialogResult is automatically set to false . The following markup has the same effect as the preceding code, without the need to handle the Click event.

A dialog box automatically returns false when a user presses the Close button in the title bar or chooses the Close menu item from the System menu.

Processing data returned from a modal dialog box

When DialogResult is set by a dialog box, the function that opened it can get the dialog box result by inspecting the DialogResult property when ShowDialog returns.

If the dialog result is true , the function uses that as a cue to retrieve and process the data provided by the user.

After ShowDialog has returned, a dialog box cannot be reopened. Instead, you need to create a new instance.

If the dialog result is false , the function should end processing appropriately.

Creating a modeless custom dialog box

A modeless dialog box, such as the Find Dialog Box shown in the following figure, has the same fundamental appearance as the modal dialog box.

However, the behavior is slightly different, as described in the following sections.

Opening a modeless dialog box

A modeless dialog box is opened by calling the Show method.

Unlike ShowDialog, Show returns immediately. Consequently, the calling window cannot tell when the modeless dialog box is closed and, therefore, does not know when to check for a dialog box result or get data from the dialog box for further processing. Instead, the dialog box needs to create an alternative way to return data to the calling window for processing.

Processing data returned from a modeless dialog box

In this example, the FindDialogBox may return one or more find results to the main window, depending on the text being searched for without any specific frequency. As with a modal dialog box, a modeless dialog box can return results using properties. However, the window that owns the dialog box needs to know when to check those properties. One way to enable this is for the dialog box to implement an event that is raised whenever text is found. FindDialogBox implements the TextFoundEvent for this purpose, which first requires a delegate.

Using the TextFoundEventHandler delegate, FindDialogBox implements the TextFoundEvent .

Consequently, Find can raise the event when a search result is found.

The owner window then needs to register with and handle this event.

Closing a modeless dialog box

Because DialogResult does not need to be set, a modeless dialog can be closed using system provide mechanisms, including the following:

Clicking the Close button in the title bar.

Choosing Close from the System menu.

Alternatively, your code can call Close when the Close button is clicked.

Оцените статью