Windows forms font bold

Практическое руководство. Задание атрибутов шрифта для элемента управления RichTextBox в Windows Forms How to: Set Font Attributes for the Windows Forms RichTextBox Control

RichTextBoxЭлемент управления Windows Forms имеет множество параметров для форматирования отображаемого текста. The Windows Forms RichTextBox control has numerous options for formatting the text it displays. Можно сделать выбранные символы полужирным, подчеркнутым или курсивом с помощью SelectionFont Свойства. You can make the selected characters bold, underlined, or italic, using the SelectionFont property. Это свойство также может использоваться для изменения размера и начертания выбранных символов. You can also use this property to change the size and typeface of the selected characters. SelectionColorСвойство позволяет изменить цвет выбранных символов. The SelectionColor property enables you to change the selected characters’ color.

Изменение внешнего вида символов To change the appearance of characters

Задайте SelectionFont для свойства соответствующий шрифт. Set the SelectionFont property to an appropriate font.

Чтобы разрешить пользователям задавать семейство шрифтов, размер и гарнитуру в приложении, обычно используется FontDialog компонент. To enable users to set the font family, size, and typeface in an application, you would typically use the FontDialog component. Его обзор приведен в разделе Общие сведения о компоненте FontDialog. For an overview, see FontDialog Component Overview.

Задайте SelectionColor для свойства соответствующий цвет. Set the SelectionColor property to an appropriate color.

Чтобы разрешить пользователям задавать цвет в приложении, обычно используется ColorDialog компонент. To enable users to set the color in an application, you would typically use the ColorDialog component. Его обзор приведен в разделе Общие сведения о компоненте ColorDialog. For an overview, see ColorDialog Component Overview.

Эти свойства влияют лишь на выделенный текст или, если никакой текст не выбран, текст, вводимый в текущей позиции курсора. These properties only affect selected text, or, if no text is selected, the text that is typed at the current location of the insertion point. Сведения о программном выборе текста см. в разделе Select . For information on selecting text programmatically, see Select.

Control. Font Свойство

Определение

Возвращает или задает шрифт текста, отображаемого элементом управления. Gets or sets the font of the text displayed by the control.

Значение свойства

Шрифт Font, применяемый к тексту, отображаемому элементом управления. The Font to apply to the text displayed by the control. Значением по умолчанию является значение свойства DefaultFont. The default is the value of the DefaultFont property.

Примеры

В следующем примере кода выводится FontDialog для пользователя и изменяется Font DateTimePicker элемент управления. The following code example displays a FontDialog to the user and changes the Font of a DateTimePicker control. В этом примере требуется, чтобы в Form Button нем было и DateTimePicker . This example requires that you have a Form with Button and a DateTimePicker on it.

Комментарии

FontСвойство является внешним свойством. The Font property is an ambient property. Внешнее свойство — это свойство элемента управления, которое, если оно не задано, извлекается из родительского элемента управления. An ambient property is a control property that, if not set, is retrieved from the parent control. Например, Button по умолчанию объект будет иметь то же значение, BackColor что и его родительский элемент Form . For example, a Button will have the same BackColor as its parent Form by default. Дополнительные сведения о внешних свойствах см. в разделе AmbientProperties класс или Control Общие сведения о классе. For more information about ambient properties, see the AmbientProperties class or the Control class overview.

Читайте также:  How to mount disks linux

Так как объект Font является неизменяемым (то есть вы не можете изменить его свойства), можно назначить только Font новое свойство Font . Because the Font is immutable (meaning that you cannot adjust any of its properties), you can only assign the Font property a new Font. Однако можно создать новый шрифт на основе существующего шрифта. However, you can base the new font on the existing font.

Ниже приведен пример того, как изменить существующий шрифт, сделав его полужирным: The following is an example of how to adjust the existing font to make it bold:

Примечания для тех, кто наследует этот метод

При переопределении Font свойства в производном классе используйте свойство базового класса Font для расширения базовой реализации. When overriding the Font property in a derived class, use the base class’s Font property to extend the base implementation. В противном случае необходимо предоставить всю реализацию. Otherwise, you must provide all the implementation. Переопределение get методов доступа и для свойства не требуется set Font ; при необходимости можно переопределить только одно из них. You are not required to override both the get and set accessors of the Font property; you can override only one if needed.

Custom .ttf fonts to use in C# windows.Form

How do I use a custom .tff font file I have with my current windows.forms application? I read some where that I use it as an embedded resource, but how do I set it the System.Drawing.Font type?

3 Answers 3

This article: How to embed a true type font shows how to do what you ask in .NET.

How to embed a True Type font

Some applications, for reasons of esthetics or a required visual style, will embed certain uncommon fonts so that they are always there when needed regardless of whether the font is actually installed on the destination system.

The secret to this is twofold. First the font needs to be placed in the resources by adding it to the solution and marking it as an embedded resource. Secondly, at runtime, the font is loaded via a stream and stored in a PrivateFontCollection object for later use.

This example uses a font which is unlikely to be installed on your system. Alpha Dance is a free True Type font that is available from the Free Fonts Collection. This font was embedded into the application by adding it to the solution and selecting the «embedded resource» build action in the properties.

Once the file has been successfully included in the resources you need to provide a PrivateFontCollection object in which to store it and a method by which it’s loaded into the collection. The best place to do this is probably the form load override or event handler. The following listing shows the process. Note how the AddMemoryFont method is used. It requires a pointer to the memory in which the font is saved as an array of bytes. In C# we can use the unsafe keyword for convienience but VB must use the capabilities of the Marshal classes unmanaged memory handling. The latter option is of course open to C# programmers who just don’t like the unsafe keyword. PrivateFontCollection pfc = new PrivateFontCollection();

Fonts may have only certain styles which are available and unfortunately, selecting a font style that doesn’t exist will throw an exception. To overcome this the font can be interrogated to see which styles are available and only those provided by the font can be used. The following listing demonstrates how the Alpha Dance font is used by checking the available font styles and showing all those that exist. Note that the underline and strikethrough styles are pseudo styles constructed by the font rendering engine and are not actually provided in glyph form.

Figure 2 shows the application in action.

Шрифты и текст Using Fonts and Text

Существует несколько классов, предлагаемых GDI+ и GDI для рисования текста на Windows Forms. There are several classes offered by GDI+ and GDI for drawing text on Windows Forms. Класс GDI+ Graphics содержит несколько DrawString методов, позволяющих задавать различные функции текста, такие как расположение, ограничивающий прямоугольник, шрифт и формат. The GDI+ Graphics class has several DrawString methods that allow you to specify various features of text, such as location, bounding rectangle, font, and format. Кроме того, можно рисовать и измерять текст с помощью GDI, используя статические DrawText методы и, MeasureText предлагаемые TextRenderer классом. In addition, you can draw and measure text with GDI using the static DrawText and MeasureText methods offered by the TextRenderer class. Методы GDI также позволяют задавать расположение, шрифт и формат. The GDI methods also allow you to specify location, font, and format. Для отрисовки текста можно выбрать либо GDI, либо GDI+. Однако GDI обычно обеспечивает лучшую производительность и более точное измерение текста. You can choose either GDI or GDI+ for text rendering; however, GDI generally offers better performance and more accurate text measuring. Другие классы, участвующие в отрисовке текста FontFamily , включают,, Font StringFormat и TextFormatFlags . Other classes that contribute to text rendering include FontFamily , Font , StringFormat, and TextFormatFlags .

Читайте также:  Принтер hp deskjet 2050 драйвера для windows 10

в этом разделе In This Section

Практическое руководство. Разработка шрифтов и их семейств How to: Construct Font Families and Fonts
Показывает, как создавать Font FontFamily объекты и. Shows how to create Font and FontFamily objects.

Практическое руководство. Рисование текста в указанной позиции How to: Draw Text at a Specified Location
Описание способов рисования текста в определенном расположении с помощью GDI+ и GDI. Describes how to draw text in a certain location using GDI+ and GDI.

Практическое руководство. Многострочный вывод текста в прямоугольнике How to: Draw Wrapped Text in a Rectangle
Описывает Рисование текста в прямоугольнике с помощью GDI+ и GDI. Explains how to draw text in a rectangle using GDI+ and GDI.

Практическое руководство. Рисование текста с использованием GDI How to: Draw Text with GDI
Демонстрирует использование GDI для рисования текста. Demonstrates how to use GDI for drawing text.

Практическое руководство. Выравнивание рисуемого текста How to: Align Drawn Text
Показывает, как форматировать текст GDI+ и GDI. Shows how to format GDI+ and GDI text.

Практическое руководство. Вывод текста по вертикали How to: Create Vertical Text
Описывает Рисование текста с выравниванием по вертикали с помощью GDI+. Describes how to draw vertically aligned text with GDI+.

Практическое руководство. Установка позиций табуляции для выводимого текста How to: Set Tab Stops in Drawn Text
Показывает, как рисовать текст с позициями табуляции с помощью GDI+. Shows how draw text with tab stops with GDI+.

Практическое руководство. Перебор установленных шрифтов How to: Enumerate Installed Fonts
Содержит сведения о том, как вывести список имен установленных шрифтов. Explains how to list the names of installed fonts.

Читайте также:  Случайно удалил мой компьютер с рабочего стола как восстановить windows 10

Практическое руководство. Получение метрик шрифтов How to: Obtain Font Metrics
Показывает, как получить метрики шрифта, такие как дохождение и спуск ячеек. Shows how to obtain font metrics such as cell ascent and descent.

Практическое руководство. Сглаживание текста How to: Use Antialiasing with Text
Объясняется, как использовать сглаживание при рисовании текста. Explains how to use antialiasing when drawing text.

Справочник Reference

Font
Описывает этот класс и содержит ссылки на все его члены. Describes this class and contains links to all of its members.

FontFamily
Описывает этот класс и содержит ссылки на все его члены. Describes this class and contains links to all of its members.

PrivateFontCollection
Описывает этот класс и содержит ссылки на все его члены. Describes this class and contains links to all of its members.

TextRenderer
Описывает этот класс и содержит ссылки на все его члены. Describes this class and contains links to all of its members.

TextFormatFlags
Описывает этот класс и содержит ссылки на все его члены. Describes this class and contains links to all of its members.

International fonts in Windows Forms and controls

In International applications, the recommended method of selecting fonts is to use font fallback wherever possible. Font fallback means that the system determines what script the character belongs to.

Using font fallback

To take advantage of this feature, don’t set the Font property for your form or any other element. The application will automatically use the default system font, which differs from one localized language of the operating system to another. When the application runs, the system will automatically provide the correct font for the culture selected in the operating system.

There’s an exception to the rule of not setting the font, which is for changing the font style. This might be important for an application in which the user clicks a button to make text in a text box appear in boldface. To do that, you would write a function to change the text box’s font style to bold, based on whatever the form’s font is. It’s important to call this function in two places: in the button’s Click event handler and in the FontChanged event handler. If the function is called only in the Click event handler and some other piece of code changes the font family of the entire form, the text box doesn’t change with the rest of the form.

However, when you localize your application, the bold font may display poorly for certain languages. If this is a concern, you want the localizers to have the option of switching the font from bold to regular text. Since localizers are typically not developers and don’t have access to source code, only to resource files, this option needs to be set in the resource files. To do this, you would set the Bold property to true . This results in the font setting being written out to the resource files, where localizers can edit it. You then write code after the InitializeComponent method to reset the font based on whatever the form’s font is, but using the font style specified in the resource file.

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