Перейти к содержимому

Что такое label в c

  • автор:

Что такое label в c

In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. The Label is a class and it is defined under System.Windows.Forms namespace. In windows form, you can create Label in two different ways:

1. Design-Time: It is the easiest method to create a Label control using the following steps:

  • Step 1: Create a windows form as shown in the below image:
    Visual Studio -> File -> New -> Project -> WindowsFormApp
  • Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
  • Step 3: After drag and drop you will go to the properties of the Label control to set the properties of the Label according to your need.

2. Run-Time: It is a little bit trickier than the above method. In this method, you can set create your own Label control using the Label class. Steps to create a dynamic label:

Что такое label в c

Label представляет обычную текстовую метку, которая выводит информацию с помощью свойства Text. Label удобен для создания заголоков и меток к элементам ввода. Основные свойства Label:

CharacterSpacing : расстояние между символами в тексте в виде значения типа double

FontAttributes : определяет стиль текста

FontAutoScalingEnabled : значение типа bool, устанавливает, будет ли к тексту применяться системное масштабирование

FontFamily : семейство шрифтов в виде строки

FontSize : размер шрифта (значение типа double)

FormattedText : представляет отформатированный текст в виде объекта FormattedString

LineBreakMode : значение типа LineBreakMode, которое определяет, как будет производиться перенос строки, если текст не вмещается

LineHeight : высота строки (значение типа double)

MaxLines : максимальное допустимое количество строк

Padding : внутренний отступ

Text : текст метки

TextColor : цвет текста

TextDecorations : декорации текста (его подчеркивание или вчеркивание) (значение типа TextDecorations)

TextTransform : объект типа TextTransform, который определяет преобразование текста

TextType : значение типа TextType, которое определяет тип текста — обычный текст или html

HorizontalTextAlignment : значение TextAlignment, которое определяет выравнивание текста по горизонтали

VerticalTextAlignment : значение типа TextAlignment, которое определяет выравнивание текста по вертикали

Пример простейшей метки

Label в .NET MAUI и C#

Аналогичный пример в XAML:

Форматирование текста

Свойство Text элемента Label позволяет устанавливать простой текст, который мы можем стилизовать с помощью ранее рассмотренных свойств. Однако текст с каким-то более сложным форматированием так не задать. И для этого в элементе Label определено вспомогательное свойство FormattedText , которое допускает сложное форматирование.

Свойство FormattedText хранит не просто строку текста, а объект типа FormattedString , который инкапсулирует объекты типа Span . Каждый объект Span как раз и представляет кусок некоторым образом стилизованного текста. Для стилизации объекта Span применются все те же свойства:

Например,создадим текст со сложным форматированием в коде:

Аналогичный код в XAML:

Форматирование текста в .NET MAUI и C#

Перевод строки

Для переноса текста на новую строку используется значение «\n». Например:

Перенос текста на новую строку в .NET MAUI и C#

В XAML тоже не сложно задать многострочный текст:

В данном случае применяется сложное свойство Label.Text , которое в качестве значения принимает объект String. Причем для элемента String применяется префикс x — x:String , то есть определение данного типа берется из пространства имен «http://schemas.microsoft.com/winfx/2009/xaml»

Обработка нажатия

Кнопки определяют событие нажатия, которое мы можем обработать. Однако у Label подобного события нет. Но что делать, если мы вдруг хотим обрабатывать нажатие на заголовок? В этом случае мы можем воспользоваться специальным классом TapGestureRecognizer , который позволяет обрабатывать нажатия:

TapGestureRecognizer представляет специальный класс, который позволяет распознать нажатия. С помощью свойства NumberOfTapsRequired мы можем установить, сколько нажатий необходимо. В данном случае мы устанавливаем двойное нажатие. И именно по двойному нажатию будет генерироваться событие Tapped , в обработчике которого изменяется значение переменной count и текст метки.

И чтобы связать объект TapGestureRecognizer с меткой, необходимо добавить этот объект в коллекцию GestureRecognizers :

C#. Windows Forms. Компонент Label. Программное создание элемента управления Label. Класс MessageBox

Компонент Label . Программное создание элемента управления Label . Класс MessageBox . Перечисление DialogResult

Содержание

  • 1. Компонент Label . Свойства компонента Label
  • 2. События компонента Label
  • 3. Программное создание элемента управления Label . Пример
  • 4. Класс MessageBox . Назначение. Пример

Поиск на других ресурсах:

1. Компонент Label . Свойства компонента Label

Компонент типа Label представляет собой статический текст на мониторе. На рисунке 1 показано размещение компонента Label на панели элементов в системе Microsoft Visual Studio 2022.

C#. Windows Forms. Компонент Label. Размещение компонента Label на форме

Рисунок 1. Компонент Label . Размещение компонента Label на форме

Основные свойства компонента Label приведены ниже.

Свойство

Описание

C#. Windows Forms. Компонент Label. Влияние свойства AutoEllipsis на вид текста

Рисунок 2. Влияние свойства AutoEllipsis на вид текста «Hello world!» : a) AutoEllipsis = True ; b) AutoEllipsis = False

C#. Windows Forms. Компонент Label. Влияние свойства AutoSize на вид текста

Рисунок 3. Влияние свойства AutoSize на вид текста «Hello world» : a) AutoSize = True ; b) AutoSize = False

2. События компонента Label

События, на которые реагирует компонент Label , описываются в следующей таблице:

Событие Описание
Click Клик с помощью мышки на элементе управления Label
DoubleClick Двойной клик мышкою на элементе управления Label
MouseClick Клик с помощью мышки на элементе управления Label . В отличие от события Click позволяет получить более полную информацию о клике: какая клавиша мышки нажата, координата (x, y) нажатия и прочее. Вся информация получается из класса MouseEventArgs .
MouseDoubleClick Двойной клик мышкой на элементе. По сравнению с DoubleClick добавляет экземпляр класса MouseEventArgs , содержащий всю необходимую информацию о сделанном клике (координата (x, y), какая клавиша нажата и т.д.).
Paint Используется для рисования графики в области элемента управления.
3. Программное создание элемента управления Label . Пример

На форме нужно разместить кнопку, например button1 и в обработчике Click этой кнопки набрать следующий текст:

После запуска программы и нажатия на кнопке появится метка Label .

4. Класс MessageBox . Назначение. Пример

Статический класс MessageBox представляет диалоговое окно, в котором можно выводить информацию (рисунок 4). Основным методом класса, выводящим диалоговое окно, является метод Show() , который имеет много перегруженных реализаций.

C#. Windows Forms. Окно вызова метода Show() класса MessageBox

Рисунок 4. Окно, которое открывается в результате вызова метода Show() класса MessageBox (один из случаев)

Использование класса эффективно, когда нужно выводить быстрые сообщения «на лету» с базовым набором стандартных кнопок и их быстрой обработкой. Таким образом, исчезает потребность в создании излишних мелких диалоговых форм, которые усложняют восприятие структуры всего проекта.

Для демонстрации использования класса MessageBox нужно разместить кнопку на форме (например, button2 ) и запрограммировать обработчик события клика на этой кнопке.

Как видно из приведенного выше примера, работа методов класса MessageBox сочетается с использованием перечисления DialogResult . В этом перечислении объявляются константы, соответствующие кодам базовых стандартных кнопок, используемых в интерфейсе Windows. К примеру, описываются кнопки Ok, Cancel, Yes и другие.

Label Control [System.Windows.Forms.Label]

Star ActiveStar ActiveStar ActiveStar ActiveStar Active

Creates a clickable text box in a GUI application. Use a label to display text strings.

  • MSDN Page: System.Windows.Forms.Label
  • Default Event: Click

Label Control [System.Windows.Forms.Label] Creates a clickable text box in a GUI application. Use a label to display text strings

Tip: To display multiple lines of text, use a Textbox or RichTextBox control.

Important properties of the Label object

Important Events:

Important properties of the Label object

Text property: Determines the text in the label

Use the Text property to set, get, or change the text that is displayed on the label.

Value type: System.String
Default value: (None)

To set the initial value of Text property, that is, the value that appears when the GUI app starts, use the Properties pane. On the Text row, type the text that appears on the Label.

To set the initial value of Text property use the Properties pane

the value that appears when the GUI app starts

NOTE: When you change the value of the Text property of a Label in the Properties pane, PowerShell Studio changes the name of the variable that stores the Label object in your script. For example, if you change the Text property value to ‘Close’, PowerShell Studio changes all references of the Label variable to $LabelClose.

To get or change the label text while the GUI app is running, use the Text property in the event handlers in your script.

To get the text in the label:

To set the text in the label use an assignment statement. You can include variables and expressions in the assigned string value.

To change the text in the label:

Tip: To direct Windows PowerShell to evaluate an expression before inserting the result in a string, use a subexpression. The syntax is $( <expression ) .

Without subexpression

With subexpression

Font property: Determines the style and size of the label text

Use the Font property to get, set, or change the font of the label text.

Value Type: System.Drawing.Font
Default: Microsoft Sans Serif 8.25.

To set the font easily, in the Properties pane for the Label, in the Font row, click the ellipsis (…) and then use the Font selector.

click the ellipsis (…) and then use the Font selector

To display the properties of the Font object, in the Properties pane, click the Font group arrow.

click the Font group arrow

To script a font change, set the Font property to a string with the Font name, size, and style.

set the Font property to a string with the Font name, size, and style

To determine other properties of the font, create a System.Drawing.Font object.

Tips:

  • To enlarge the label automatically to fit its contents, set the AutoSize property of the Label to $True.
  • When scripting a font, be sure to set the Font property of the Label. The Text property of the Label does not have a Font property.

ForeColor property: Determines the color of the label text.

Use the ForeColor property to get, set, and change the color of the text in the label.

Values: Any [System.Drawing.Color] type
Default: ControlText (Black)

To set the ForeColor property in the Properties pane.

ForeColor property in the Properties pane

ForeColor example

To set ForeColor property in a script:

BackColor property: Determines the color of the background in the label

Use the BackColor property to get, set, and change the color of the label background.

Value Type: [System.Drawing.Color]
Default: (Determined by the operating system. Typically ‘Control’)

To set the BackColor property in a script:

BackColor example

TextAlign property: Determines the position of the text in the label

Use the TextAlign property to get, set, or change the alignment of the text relative to the label border.

Value Type: [System.Drawing.ContentAlignment] enumeration
Values: TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight
Default: MiddleCenter
To set the TextAlign property in the Property pane:

set the TextAlign property in the Property pane

To set the TextAlign property in a script:

BorderStyle property: Determines the style and thickness of the label border.

Use the BorderStyle property to get, set, or change the label border. Label borders are fixed. The end-user cannot resize any label border style.

Value Type: [System.Windows.Forms.BorderStyle] enumerator.
Values: None, FixedSingle, Fixed3D
Default: None

BorderStyle example - none

BorderStyle example - FixedSingle

BorderStyle example - Fixed3D

Image property: Determines that image that appears on the label

Use this property to display an icon, bitmap, or image of any type on the label.

Value Type: [System.Drawing.Image]
Default: (None; Same as Form.BackgroundImage)

To add an image from a file to a label, use Image property in the Property pane. Click the ellipsis and, in File Explorer, select a file. PowerShell Studio converts the file into a bitmap string (64-bit byte array) so it is independent of the local system.

To add an image from a file to a label, use Image property in the Property pane

Label example

Tip: If you are using a label to display an image without text, consider using a PictureBox object.

Note: To add an image to a label, PowerShell Studio converts the image to a 64-bit string and then uses the FromBase64String static method to pass a byte array as the System.Drawing.Image type. It does not pass a path or use any local system values.

Enabled property: Determines whether the label can be clicked

Use the Enabled property to temporarily enable or disable the click feature of the label. For example, use Enabled = $false to disable the click feature after the label has been clicked or while a function is running.

Value Type: [System.Boolean] ($True, $False).
Default: $True

To completely disable the click feature of the label, omit the Click event handler or enter an empty script block.

To set the Enabled property in the script:

AutoSize property: Adjusts the label length to enclose its contents

The AutoSize property automatically adjusts the length of the label (horizontally) to enclose the string in the value of its Text property.

Use an AutoSize value of $True when the contents of the label are not predetermined, such as when the label displays a value that is returned at runtime or the label can display text in multiple languages. To resize the label or set a fixed size, use $False.

Value Type: [System.Boolean] ($True, $False).
Default: $True (PowerShell Studio 5.2.124 and later. Otherwise, $False)

When the value of AutoSize is $True, Windows automatically resizes the label at runtime to display the text within the label borders.

Label AutoSize TrueFalse

The size of the label in the designer might not indicate its actual size when the form is displayed.

AutoSizeTrue

When the value of AutoSize is $False, you determine the label size, which is fixed, regardless of its content. To resize the label, the value of AutoSize must be $False.

AutoSizeFalse

AutoSize extends only the length of the label (horizontally) and the Label control does not have a MultiLine property. If the text exceeds the length of the form, the label and its text are truncated.

AutoSizeNoWrap

To use an ellipsis to prevent truncated text, set the value of AutoEllipsis to $True and AutoSize to $False.

AutoEllipsis

To wrap the text in a Label to the next line, set AutoSize to $False and then increase the height of the label (vertically).

Label AutoSize Wrap

Important Events:

Click event: Determines how the label responds when a user clicks it.

The event handler for the Click event is called when the label is clicked.

IMPORTANT: The Click event is included because it’s the default event for the Label control. However, because the Label is static, not obviously clickable, and provides no user feedback when clicked, best practice guidelines recommend using a Button or LinkLabel control for most clicking actions.

Before Click event:

Label Click Before

After Click event:

Label Click After

Note about events:

To discover which control called the event script block, use the $this automatic variable. The $this variable is particularly useful when you have multiple controls calling the same event script block. The $this variable tells which control triggered the event, so you can respond in a control-specific way.

For example, this Click event script block disables the control that called it:

Looking for more Spotlight articles? In PowerShell Studio, in the Toolbox or in the Properties pane, right-click a control and then click ‘View Spotlight Article’.

June Blender is a technology evangelist at SAPIEN Technologies, Inc. You can reach her at This email address is being protected from spambots. You need JavaScript enabled to view it. or follow her on Twitter at @juneb_get_help.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *