Font Classe

Definição

Define um formato particular para o texto, incluindo fontes de letra, tamanho e atributos de estilo. Esta classe não pode ser herdada.

public ref class Font sealed : MarshalByRefObject, ICloneable, IDisposable, System::Runtime::Serialization::ISerializable
[System.ComponentModel.TypeConverter(typeof(System.Drawing.FontConverter))]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public sealed class Font : MarshalByRefObject, ICloneable, IDisposable, System.Runtime.Serialization.ISerializable
[<System.ComponentModel.TypeConverter(typeof(System.Drawing.FontConverter))>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Serializable>]
type Font = class
    inherit MarshalByRefObject
    interface ICloneable
    interface ISerializable
    interface IDisposable
Public NotInheritable Class Font
Inherits MarshalByRefObject
Implements ICloneable, IDisposable, ISerializable
Herança
Atributos
Implementações

Exemplos

O exemplo de código seguinte demonstra como usar o Font construtor e as Sizepropriedades , SizeInPoints, e Unit . Este exemplo foi concebido para ser usado com uma Windows Form que contém um ComboBox chamado ComboBox1 que é preenchido com as cadeias "Bigger" e "Smaller" e um Label chamado Label1. Cole o código seguinte no formulário e associe o ComboBox1_SelectedIndexChanged método ao SelectedIndexChanged evento do ComboBox controlo.

private:
    void ComboBox1_SelectedIndexChanged(System::Object^ sender,
        System::EventArgs^ e)
    {

        // Cast the sender object back to a ComboBox.
        ComboBox^ ComboBox1 = (ComboBox^) sender;

        // Retrieve the selected item.
        String^ selectedString = (String^) ComboBox1->SelectedItem;

        // Convert it to lowercase.
        selectedString = selectedString->ToLower();

        // Declare the current size.
        float currentSize;

        // If Bigger is selected, get the current size from the 
        // Size property and increase it. Reset the font to the
        //  new size, using the current unit.
        if (selectedString == "bigger")
        {
            currentSize = Label1->Font->Size;
            currentSize += 2.0F;
            Label1->Font =gcnew System::Drawing::Font(Label1->Font->Name, 
                currentSize, Label1->Font->Style, Label1->Font->Unit);

        }
        // If Smaller is selected, get the current size, in
        // points, and decrease it by 2.  Reset the font with
        // the new size in points.
        if (selectedString == "smaller")
        {
            currentSize = Label1->Font->Size;
            currentSize -= 2.0F;
            Label1->Font = gcnew System::Drawing::Font(Label1->Font->Name, 
                currentSize, Label1->Font->Style);

        }
    }
private void ComboBox1_SelectedIndexChanged(System.Object sender, 
    System.EventArgs e)
{

    // Cast the sender object back to a ComboBox.
    ComboBox ComboBox1 = (ComboBox) sender;

    // Retrieve the selected item.
    string selectedString = (string) ComboBox1.SelectedItem;

    // Convert it to lowercase.
    selectedString = selectedString.ToLower();

    // Declare the current size.
    float currentSize;

    // Switch on the selected item. 
    switch(selectedString)
    {

            // If Bigger is selected, get the current size from the 
            // Size property and increase it. Reset the font to the
            //  new size, using the current unit.
        case "bigger":
            currentSize = Label1.Font.Size;
            currentSize += 2.0F;
            Label1.Font = new Font(Label1.Font.Name, currentSize, 
                Label1.Font.Style, Label1.Font.Unit);

            // If Smaller is selected, get the current size, in points,
            // and decrease it by 1.  Reset the font with the new size
            // in points.
            break;
        case "smaller":
            currentSize = Label1.Font.SizeInPoints;
            currentSize -= 1;
            Label1.Font = new Font(Label1.Font.Name, currentSize, 
                Label1.Font.Style);
            break;
    }
}
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged

    ' Cast the sender object back to a ComboBox.
    Dim ComboBox1 As ComboBox = CType(sender, ComboBox)

    ' Retrieve the selected item.
    Dim selectedString As String = CType(ComboBox1.SelectedItem, String)

    ' Convert it to lowercase.
    selectedString = selectedString.ToLower()

    ' Declare the current size.
    Dim currentSize As Single

    ' Switch on the selected item. 
    Select Case selectedString

        ' If Bigger is selected, get the current size from the 
        ' Size property and increase it. Reset the font to the
        '  new size, using the current unit.
    Case "bigger"
            currentSize = Label1.Font.Size
            currentSize += 2.0F
            Label1.Font = New Font(Label1.Font.Name, currentSize, _
                Label1.Font.Style, Label1.Font.Unit)

            ' If Smaller is selected, get the current size, in points,
            ' and decrease it by 1.  Reset the font with the new size
            ' in points.
        Case "smaller"
            currentSize = Label1.Font.SizeInPoints
            currentSize -= 1
            Label1.Font = New Font(Label1.Font.Name, currentSize, _
                Label1.Font.Style)
    End Select
End Sub

Observações

Para mais informações sobre como construir fontes, veja Como: Construir Famílias de Fontes e Fontes. As aplicações Windows Forms suportam fontes TrueType e têm suporte limitado para fontes OpenType. Se tentar usar uma fonte que não é suportada, ou se a fonte não estiver instalada na máquina que está a executar a aplicação, a fonte Microsoft Sans Serif será substituída.

Note

No .NET 6 e versões posteriores, o pacote System.Drawing.Common, que inclui esse tipo, só é suportado em sistemas operacionais Windows. O uso deste tipo em aplicações multiplataforma causa avisos em tempo de compilação e exceções em tempo de execução. Para obter mais informações, consulte System.Drawing.Common suportado apenas no Windows.

Construtores

Name Description
Font(Font, FontStyle)

Inicializa um novo Font que utiliza o existente Font especificado e FontStyle a enumeração.

Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean)

Inicializa um novo Font usando um tamanho, estilo, unidade e conjunto de caracteres especificados.

Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte)

Inicializa um novo Font usando um tamanho, estilo, unidade e conjunto de caracteres especificados.

Font(FontFamily, Single, FontStyle, GraphicsUnit)

Inicializa um novo Font usando um tamanho, estilo e unidade especificados.

Font(FontFamily, Single, FontStyle)

Inicializa um novo Font usando um tamanho e estilo especificados.

Font(FontFamily, Single, GraphicsUnit)

Inicializa um novo Font usando um tamanho e unidade especificados. Define o estilo para Regular.

Font(FontFamily, Single)

Inicializa um novo Font usando um tamanho especificado.

Font(String, Single, FontStyle, GraphicsUnit, Byte, Boolean)

Inicializa um novo Font usando o tamanho, estilo, unidade e conjunto de caracteres especificados.

Font(String, Single, FontStyle, GraphicsUnit, Byte)

Inicializa um novo Font usando um tamanho, estilo, unidade e conjunto de caracteres especificados.

Font(String, Single, FontStyle, GraphicsUnit)

Inicializa um novo Font usando um tamanho, estilo e unidade especificados.

Font(String, Single, FontStyle)

Inicializa um novo Font usando um tamanho e estilo especificados.

Font(String, Single, GraphicsUnit)

Inicializa um novo Font usando um tamanho e unidade especificados. O estilo está definido para Regular.

Font(String, Single)

Inicializa um novo Font usando um tamanho especificado.

Propriedades

Name Description
Bold

Obtém um valor que indica se isto Font está a negrito.

FontFamily

Fica associado FontFamily a isto Font.

GdiCharSet

Recebe um valor de byte que especifica o conjunto de caracteres GDI que este Font utilizador utiliza.

GdiVerticalFont

Obtém um valor booleano que indica se isto Font deriva de uma fonte vertical GDI.

Height

Obtém o espaçamento das linhas desta fonte.

IsSystemFont

Obtém um valor que indica se a fonte é membro de SystemFonts.

Italic

Recebe um valor que indica se esta fonte tem o estilo itálico aplicado.

Name

Obtém o nome da cara disto Font.

OriginalFontName

Recebe o nome da fonte originalmente especificada.

Size

Obtém o tamanho em deste Font medido nas unidades especificadas pela Unit propriedade.

SizeInPoints

Obtém o tamanho em, em pontos, deste Font.

Strikeout

Obtém um valor que indica se isto Font especifica uma linha horizontal através da fonte.

Style

Obtém informações de estilo para isto Font.

SystemFontName

Obtém o nome da fonte do sistema se a IsSystemFont propriedade devolver true.

Underline

Recebe um valor que indica se isto Font está sublinhado.

Unit

Obtém a unidade de medida para isto Font.

Métodos

Name Description
Clone()

Cria uma cópia exata deste Font.

CreateObjRef(Type)

Cria um objeto que contém toda a informação relevante necessária para gerar um proxy usado para comunicar com um objeto remoto.

(Herdado de MarshalByRefObject)
Dispose()

Liberta todos os recursos utilizados por este Font.

Equals(Object)

Indica se o objeto especificado é a Font e tem os mesmos FontFamilyvalores , GdiVerticalFont, GdiCharSet, StyleSize, , e Unit propriedades que este Font.

Finalize()

Permite que um objeto tente libertar recursos e realizar outras operações de limpeza antes de ser recuperado pela recolha de lixo.

FromHdc(IntPtr)

Cria um Font a partir do handle de Windows especificado para o contexto de um dispositivo.

FromHfont(IntPtr)

Cria um Font a partir do handle de Windows especificado.

FromLogFont(Object, IntPtr)

Cria uma Font a partir da estrutura de fonte lógica GDI especificada (LOGFONT).

FromLogFont(Object)

Cria uma Font a partir da estrutura de fonte lógica GDI especificada (LOGFONT).

GetHashCode()

Obtém o código de hash para isto Font.

GetHeight()

Devolve o espaçamento entre linhas, em pixels, desta fonte.

GetHeight(Graphics)

Devolve o espaçamento entre linhas, na unidade atual de um especificado Graphics, desta fonte.

GetHeight(Single)

Devolve a altura, em pixels, deste Font quando desenhado para um dispositivo com a resolução vertical especificada.

GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de vida útil neste caso.

(Herdado de MarshalByRefObject)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
InitializeLifetimeService()

Obtém-se um objeto de serviço vitalício para controlar a apólice vitalícia neste caso.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto atual MarshalByRefObject .

(Herdado de MarshalByRefObject)
ToHfont()

Devolve uma pega a este Font.

ToLogFont(Object, Graphics)

Cria uma estrutura de fonte lógica GDI (LOGFONT) a partir deste Font.

ToLogFont(Object)

Cria uma estrutura de fonte lógica GDI (LOGFONT) a partir deste Font.

ToString()

Devolve uma representação de cadeias legível por humanos deste Font.

Implementações de Interface Explícita

Name Description
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Preenche a SerializationInfo com os dados necessários para serializar o objeto alvo.

Aplica-se a

Ver também