- Как задать подсказки для элементов управления в форме Windows во время разработки How to: Set ToolTips for controls on a Windows Form at design time
- Программное задание подсказки Set a ToolTip programmatically
- Задание подсказки в конструкторе Set a ToolTip in the designer
- Удаление подсказки программными средствами To remove a ToolTip programmatically
- Удаление подсказки в конструкторе Remove a ToolTip in the designer
- Общие сведения о компоненте ToolTip (Windows Forms) ToolTip Component Overview (Windows Forms)
- Работа с компонентом ToolTip Working with the ToolTip Component
- Компонент ToolTip (Windows Forms) ToolTip Component (Windows Forms)
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- Tool Tip Класс
- Определение
- Примеры
- Комментарии
- Конструкторы
- Свойства
- Методы
- События
Как задать подсказки для элементов управления в форме Windows во время разработки How to: Set ToolTips for controls on a Windows Form at design time
Строку можно задать ToolTip в коде или в конструктор Windows Forms в Visual Studio. You can set a ToolTip string in code or in the Windows Forms Designer in Visual Studio. Дополнительные сведения о ToolTip компоненте см. в разделе Общие сведения о компоненте ToolTip. For more information about the ToolTip component, see ToolTip Component Overview.
Программное задание подсказки Set a ToolTip programmatically
Добавьте элемент управления, который будет отображать подсказку. Add the control that will display the ToolTip.
Используйте SetToolTip метод ToolTip компонента. Use the SetToolTip method of the ToolTip component.
Задание подсказки в конструкторе Set a ToolTip in the designer
В Visual Studio добавьте компонент в ToolTip форму. In Visual Studio, add a ToolTip component to the form.
Выберите элемент управления, который будет отображать подсказку, или добавьте его в форму. Select the control that will display the ToolTip, or add it to the form.
В окне » Свойства » установите подсказку для значения ToolTip1 в соответствующую строку текста. In the Properties window, set the ToolTip on ToolTip1 value to an appropriate string of text.
Удаление подсказки программными средствами To remove a ToolTip programmatically
Используйте SetToolTip метод ToolTip компонента. Use the SetToolTip method of the ToolTip component.
Удаление подсказки в конструкторе Remove a ToolTip in the designer
В Visual Studio выберите элемент управления, отображающий подсказку. In Visual Studio, select the control that is displaying the ToolTip.
В окне Свойства удалите текст из подсказки в ToolTip1. In the Properties window, delete the text in the ToolTip on ToolTip1.
Общие сведения о компоненте ToolTip (Windows Forms) ToolTip Component Overview (Windows Forms)
Компонент ToolTip в Windows Forms отображает текст при наведении указателя мыши на элементы управления. The Windows Forms ToolTip component displays text when the user points at controls. Компонент ToolTip можно связать с любым элементом управления. A ToolTip can be associated with any control. Пример использования этого компонента: для экономии пространства в форме можно отобразить маленький значок на кнопке и использовать подсказку для объяснения функции кнопки. An example use of this component: to save space on a form, you can display a small icon on a button and use a ToolTip to explain the button’s function.
Работа с компонентом ToolTip Working with the ToolTip Component
ToolTipКомпонент предоставляет ToolTip свойство для нескольких элементов управления в форме Windows или другом контейнере. A ToolTip component provides a ToolTip property to multiple controls on a Windows Form or other container. Например, если поместить один ToolTip компонент в форму, можно отобразить «введите здесь свое имя» для TextBox элемента управления и «щелкните здесь, чтобы сохранить изменения» для Button элемента управления. For example, if you place one ToolTip component on a form, you can display «Type your name here» for a TextBox control and «Click here to save changes» for a Button control.
Ключевыми методами ToolTip компонента являются SetToolTip и GetToolTip . The key methods of the ToolTip component are SetToolTip and GetToolTip. Можно использовать метод, SetToolTip чтобы задать всплывающие подсказки, отображаемые для элементов управления. You can use the SetToolTip method to set the ToolTips displayed for controls. Дополнительные сведения см. в разделе как задать подсказки для элементов управления в форме Windows во время разработки. For more information, see How to: Set ToolTips for Controls on a Windows Form at Design Time. Ключевыми свойствами являются Active , для отображения которых отображается true всплывающая подсказка, и AutomaticDelay , которая задает продолжительность отображения строки подсказки, время, в течение которого пользователь должен указывать на элемент управления для отображения всплывающей подсказки, а также время, затрачиваемое на отображение последующих окон всплывающей подсказки. The key properties are Active, which must be set to true for the ToolTip to appear, and AutomaticDelay, which sets the length of time that the ToolTip string is shown, how long the user must point at the control for the ToolTip to appear, and how long it takes for subsequent ToolTip windows to appear. Дополнительные сведения см. в разделе как изменить задержку Windows Forms компонента ToolTip. For more information, see How to: Change the Delay of the Windows Forms ToolTip Component.
Компонент ToolTip (Windows Forms) ToolTip Component (Windows Forms)
Компонент ToolTip в Windows Forms отображает текст при наведении указателя мыши на элементы управления. The Windows Forms ToolTip component displays text when the user points at controls. Компонент ToolTip можно связать с любым элементом управления. A ToolTip can be associated with any control. Пример использования этого компонента: для экономии места в форме можно настроить отображение маленького значка для кнопки и использовать компонент ToolTip для объяснения ее функции. An example use of this control: In order to save space on a form, you can display a small icon on a button and use a ToolTip to explain the button’s function.
в этом разделе In This Section
Общие сведения об элементе управления ToolTip ToolTip Component Overview
Основные понятия, связанные с компонентом ToolTip, который позволяет пользователям просматривать текст при наведении указателя мыши на элемент управления. Introduces the general concepts of the ToolTip component, which allows users to see text when they point the mouse at a control.
Практическое руководство. Изменение значения задержки для компонента ToolTip в Windows Forms How to: Change the Delay of the Windows Forms ToolTip Component
Описание настройки значений, определяющих время задержки отображения подсказки, а также время, в течение которого она отображается. Explains how to set values that control how long a Tooltip takes to appear and the length of time for which it is shown.
Справочник Reference
Класс ToolTip ToolTip class
Справочная информация о классе и его членах. Provides reference information on the class and its members.
Связанные разделы Related Sections
Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Полный список элементов управления Windows Forms со ссылками на информацию об их применении. Provides a complete list of Windows Forms controls, with links to information on their use.
Отображение справки по элементам управления с помощью всплывающих подсказок Control Help Using ToolTips
Описание использования подсказок в качестве кратких специализированных справочных сообщений для отдельных элементов управления в формах Windows Forms. Discusses Tooltips as a way to make brief, specialized Help messages for individual controls on Windows Forms.
Tool Tip Класс
Определение
Представляет небольшое прямоугольное всплывающее окно, в котором отображается краткое описание назначения элемента управления, когда пользователь наводит указатель мыши на элемент управления. Represents a small rectangular pop-up window that displays a brief description of a control’s purpose when the user rests the pointer on the control.
Примеры
В следующем примере кода создается экземпляр ToolTip класса и связывается с экземпляром Form , в котором создается экземпляр. The following code example creates an instance of the ToolTip class and associates the instance with the Form that the instance is created within. Затем код инициализирует свойства задержки AutoPopDelay , InitialDelay и ReshowDelay . The code then initializes the delay properties AutoPopDelay, InitialDelay, and ReshowDelay. Кроме того, экземпляр ToolTip класса задает для свойства значение ShowAlways , чтобы true Разрешить отображение текста подсказки всегда независимо от того, активна ли эта форма. In addition the instance of the ToolTip class sets the ShowAlways property to true to enable ToolTip text to always be display regardless of whether the form is active. Наконец, в примере текст подсказки связывается с двумя элементами управления в форме — Button и CheckBox . Finally, the example associates ToolTip text with two controls on a form, a Button and a CheckBox. В этом примере кода требуется, чтобы метод, определенный в примере, размещался в Form , который содержит Button элемент управления с именем button1 и CheckBox элемент управления с именем checkBox1 , а также что метод вызывается из конструктора Form . The code example requires that the method defined in the example is located within a Form that contains a Button control named button1 and a CheckBox control named checkBox1 , and that the method is called from the constructor of the Form.
Комментарии
С помощью ToolTip класса можно предоставить указания пользователю, когда пользователь помещает указатель мыши на элемент управления. With the ToolTip class, you can provide hints to a user when the user places the pointer on a control. ToolTipКласс обычно используется для оповещения пользователей о предполагаемом использовании элемента управления. The ToolTip class is typically used to alert users to the intended use of a control. Например, можно указать текст подсказки для TextBox элемента управления, который принимает имя, указав формат имени, вводимого в элемент управления. For example, you can specify ToolTip text for a TextBox control that accepts a name, specifying the format of the name to be typed into the control. Кроме указания, можно также использовать ToolTip класс для предоставления сведений о состоянии времени выполнения. In addition to providing hints, you can also use the ToolTip class to provide run time status information. Например, можно использовать ToolTip класс для отображения скорости подключения и данных качества линии, когда пользователь перемещает указатель мыши на PictureBox элемент управления, отображающий состояние подключения к Интернету. For example, you can use the ToolTip class to display connection speed and line quality data when the user moves the pointer onto a PictureBox control that displays Internet connection status.
ToolTipКласс может использоваться в любом контейнере. The ToolTip class can be used in any container. Чтобы явно указать контейнер, используйте ToolTip(IContainer) конструктор. To explicitly specify a container, use the ToolTip(IContainer) constructor. Для ToolTip создания подсказок для нескольких элементов управления в одной форме обычно используется один компонент. A single ToolTip component typically is used to create ToolTips for multiple controls on a single form. После создания ToolTip Используйте отдельный вызов SetToolTip метода, чтобы связать отображаемый текст подсказки с отдельным элементом управления. After you create a ToolTip, use a separate call to the SetToolTip method to associate ToolTip display text to an individual control. Затем, когда пользователь перемещает указатель мыши на элемент управления, отображается подсказка с текстом. Then when the user moves the pointer on a control, the ToolTip with its text is displayed. Можно вызвать SetToolTip несколько раз для одного и того же элемента управления, чтобы изменить текст, связанный с элементом управления. You can call SetToolTip more than once for the same control to change the text that is associated with the control. Чтобы получить текст, связанный с элементом управления, используйте GetToolTip метод. To get the text that is associated with a control, use the GetToolTip method. Чтобы удалить все связи текста всплывающих подсказок с экземпляром ToolTip класса, используйте RemoveAll метод. To remove all ToolTip text associations with an instance of the ToolTip class, use the RemoveAll method.
Текст подсказки не отображается для отключенных элементов управления. ToolTip text is not displayed for controls that are disabled. Если ShowAlways свойство не имеет значение true , подсказки не отображаются, если их контейнер неактивен. Unless the ShowAlways property is set to true , ToolTips are not displayed when their container is inactive.
ToolTipКласс предоставляет следующие свойства и методы для изменения поведения по умолчанию и внешнего вида всплывающей подсказки. The ToolTip class provides the following properties and methods to modify the default behavior and appearance of a ToolTip.
Категория Category | Связанные члены Associated members |
---|---|
Отображение вручную Manual display | Active, Show, Hide, ShowAlways, Popup, StopTimer Active, Show, Hide, ShowAlways, Popup, StopTimer |
Время подсказок ToolTip timing | AutoPopDelay, InitialDelay, ReshowDelay, AutomaticDelay, StopTimer AutoPopDelay, InitialDelay, ReshowDelay, AutomaticDelay, StopTimer |
Content Content | SetToolTip, GetToolTip, StripAmpersands, ToolTipIcon, ToolTipTitle, RemoveAll SetToolTip, GetToolTip, StripAmpersands, ToolTipIcon, ToolTipTitle, RemoveAll |
Внешний вид Appearance | BackColor, ForeColor, IsBalloon, OwnerDraw, UseAnimation, UseFading BackColor, ForeColor, IsBalloon, OwnerDraw, UseAnimation, UseFading |
Если вы хотите отключить весь текст подсказки, чтобы он не отображался в приложении, можно использовать Active свойство. If you want to disable all ToolTip text so that it cannot be displayed in your application, you can use the Active property. Как правило, всплывающая подсказка нарисовывается операционной системой, но для настройки внешнего вида ToolTip можно задать OwnerDraw свойству значение true и выполнить обработку Draw события. Usually the ToolTip is drawn by the operating system, but to customize the appearance of the ToolTip, you can set the OwnerDraw property to true and handle the Draw event.
ToolTipTitleКласс реализует System.ComponentModel.IExtenderProvider интерфейс, который имеет один метод CanExtend . The ToolTipTitle class implements the System.ComponentModel.IExtenderProvider interface, which has a single method, CanExtend. Подсказки расширяют элементы управления в той же форме во время разработки, добавляя ToolTip свойство. ToolTips extend controls on the same form at design time, adding a ToolTip property. Дополнительные сведения о поставщиках расширений см. в разделе поставщики расширителей. For more information about extender providers, see Extender Providers.
Конструкторы
Инициализирует новый экземпляр класса ToolTip без указания контейнера. Initializes a new instance of the ToolTip without a specified container.
Инициализирует новый экземпляр класса ToolTip, используя заданный контейнер. Initializes a new instance of the ToolTip class with a specified container.
Свойства
Возвращает или задает значение, указывающее, активна ли в настоящий момент всплывающая подсказка. Gets or sets a value indicating whether the ToolTip is currently active.
Возвращает или задает автоматическую задержку всплывающей подсказки. Gets or sets the automatic delay for the ToolTip.
Возвращает или задает интервал времени, в течение которого всплывающая подсказка отображается на экране, когда указатель мыши останавливается в границах элемента управления с текстом данной подсказки. Gets or sets the period of time the ToolTip remains visible if the pointer is stationary on a control with specified ToolTip text.
Возвращает или задает цвет фона для всплывающей подсказки. Gets or sets the background color for the ToolTip.
Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.
(Унаследовано от Component)
Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.
(Унаследовано от Component)
Возвращает параметры создания для окна всплывающей подсказки. Gets the creation parameters for the ToolTip window.
Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.
(Унаследовано от Component)
Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.
(Унаследовано от Component)
Возвращает или задает цвет для всплывающей подсказки. Gets or sets the foreground color for the ToolTip.
Возвращает или задает интервал времени перед появлением всплывающей подсказки. Gets or sets the time that passes before the ToolTip appears.
Возвращает или задает значение, указывающее, должна ли всплывающая подсказка использовать всплывающее окно. Gets or sets a value indicating whether the ToolTip should use a balloon window.
Возвращает или задает значение, указывающее, выводится ли всплывающая подсказка операционной системой или кодом разработчика. Gets or sets a value indicating whether the ToolTip is drawn by the operating system or by code that you provide.
Возвращает или задает интервал времени, который должен пройти перед появлением окна очередной всплывающей подсказки при перемещении указателя мыши с одного элемента управления на другой. Gets or sets the length of time that must transpire before subsequent ToolTip windows appear as the pointer moves from one control to another.
Возвращает или задает значение, указывающее, отображается ли окно всплывающей подсказки, если родительский элемент управления не активен. Gets or sets a value indicating whether a ToolTip window is displayed, even when its parent control is not active.
Получает или задает ISite объекта Component. Gets or sets the ISite of the Component.
(Унаследовано от Component)
Возвращает или задает значение, определяющее способ обработки знаков амперсанда (&). Gets or sets a value that determines how ampersand (&) characters are treated.
Получает или задает объект, содержащий предоставленные программистом данные, связанные с объектом ToolTip. Gets or sets the object that contains programmer-supplied data associated with the ToolTip.
Возвращает или задает значение, определяющее тип значка, отображаемого вместе с текстом всплывающей подсказки. Gets or sets a value that defines the type of icon to be displayed alongside the ToolTip text.
Возвращает или задает заголовок окна всплывающей подсказки. Gets or sets a title for the ToolTip window.
Возвращает или задает значение, определяющее, должен ли при отображении всплывающей подсказки использоваться эффект анимации. Gets or sets a value determining whether an animation effect should be used when displaying the ToolTip.
Возвращает или задает значение, определяющее, должен ли при отображении всплывающей подсказки использоваться эффект затухания. Gets or sets a value determining whether a fade effect should be used when displaying the ToolTip.
Методы
Возвращает значение true , если всплывающая подсказка может предложить свойство средства расширения для заданного целевого компонента. Returns true if the ToolTip can offer an extender property to the specified target component.
Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
(Унаследовано от MarshalByRefObject)
Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.
(Унаследовано от Component)
Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.
Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы. Releases the unmanaged resources used by the Component and optionally releases the managed resources.
(Унаследовано от Component)
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
Освобождает неуправляемые ресурсы и выполняет другие операции очистки перед утилизацией объекта Cursor во время сборки мусора. Releases the unmanaged resources and performs other cleanup operations before the Cursor is reclaimed by the garbage collector.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.
(Унаследовано от Component)
Извлекает текст всплывающей подсказки, связанный с указанным элементом управления. Retrieves the ToolTip text associated with the specified control.
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
(Унаследовано от Object)
Скрывает заданное окно всплывающей подсказки. Hides the specified ToolTip window.
Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.
(Унаследовано от MarshalByRefObject)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.
(Унаследовано от MarshalByRefObject)
Удаляет весь текст всплывающей подсказки, связанной с компонентом ToolTip. Removes all ToolTip text currently associated with the ToolTip component.
Связывает текст всплывающей подсказки с указанным элементом управления. Associates ToolTip text with the specified control.
Задает текст всплывающей подсказки, связанный с указанным элементом управления, и отображает всплывающую подсказку в модальном режиме. Sets the ToolTip text associated with the specified control, and displays the ToolTip modally.
Задает текст всплывающей подсказки, связанный с указанным элементом управления, а затем отображает всплывающую подсказку в течение заданного времени. Sets the ToolTip text associated with the specified control, and then displays the ToolTip for the specified duration.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в модальном режиме в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip modally at the specified relative position.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в течение указанного времени в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip for the specified duration at the specified relative position.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в модальном режиме в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip modally at the specified relative position.
Задает текст всплывающей подсказки, связанной с указанным элементом управления, а затем отображает всплывающую подсказку в течение указанного времени в заданной относительной позиции. Sets the ToolTip text associated with the specified control, and then displays the ToolTip for the specified duration at the specified relative position.
Останавливает таймер, скрывающий отображенные всплывающие подсказки. Stops the timer that hides displayed ToolTips.
Возвращает строковое представление для этого элемента управления. Returns a string representation for this control.
События
Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.
(Унаследовано от Component)
Происходит при отображении всплывающей подсказки, если для свойства OwnerDraw установлено значение true , а для свойства IsBalloon — значение false . Occurs when the ToolTip is drawn and the OwnerDraw property is set to true and the IsBalloon property is false .
Происходит перед первоначальным отображением всплывающей подсказки. Occurs before a ToolTip is initially displayed. Это событие по умолчанию для класса ToolTip. This is the default event for the ToolTip class.