Как добавить шрифт в windows forms

I want to embed fonts in my WinForms application so that I don't have to worry about them being installed on the machine. I've searched a bit on the MSDN site and found a few hints about using native

I want to embed fonts in my WinForms application so that I don’t have to worry about them being installed on the machine. I’ve searched a bit on the MSDN site and found a few hints about using native Windows API calls, for instance Michael Caplan’s (sp?) tutorial linked to by Scott Hanselman. Now, do I really have to go through all that trouble? Can’t I just use the resource part of my app?

If not I’ll probably go the installing route. In that case, can I do that programmatically? By just copying the font file to the WindowsFonts folder?

I am aware of licensing issues.

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

asked Feb 17, 2009 at 9:59

Niklas Winde's user avatar

Niklas WindeNiklas Winde

1,7733 gold badges23 silver badges33 bronze badges

1

This is what worked for me in VS 2013, without having to use an unsafe block.

Embed the resource

  1. Double-click Resources.resx, and in the toolbar for the designer click Add Resource/Add Existing File and select your .ttf file
  2. In your solution explorer, right-click your .ttf file (now in a Resources folder) and go to Properties. Set the Build Action to «Embedded Resource»

Load the font into memory

  1. Add using System.Drawing.Text; to your Form1.cs file

  2. Add code above and inside your default constructor to create the font in memory (without using «unsafe» as other examples have shown). Below is my entire Form1.cs:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Reflection;
    
    using System.Drawing.Text;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            [System.Runtime.InteropServices.DllImport("gdi32.dll")]
            private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
                IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);
    
            private PrivateFontCollection fonts = new PrivateFontCollection();
    
            Font myFont;
    
            public Form1()
            {
                InitializeComponent();
    
                byte[] fontData = Properties.Resources.MyFontName;
                IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
                System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
                uint dummy = 0;
                fonts.AddMemoryFont(fontPtr, Properties.Resources.MyFontName.Length);
                AddFontMemResourceEx(fontPtr, (uint)Properties.Resources.MyFontName.Length, IntPtr.Zero, ref dummy);
                System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);
    
                myFont = new Font(fonts.Families[0], 16.0F);
            }
        }
    }
    

Use your font

  1. Add a label to your main form, and add a load event to set the font in Form1.cs:

    private void Form1_Load(object sender, EventArgs e)
    {
        label1.Font = myFont;
    }
    

answered May 7, 2014 at 13:40

knighter's user avatar

6

// specify embedded resource name
string resource = "embedded_font.PAGAP___.TTF";

// receive resource stream
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);

// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);

// create a buffer to read in to
byte[] fontdata = new byte[fontStream.Length];

// read the font data from the resource
fontStream.Read(fontdata, 0, (int)fontStream.Length);

// copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);

// pass the font to the font collection
private_fonts.AddMemoryFont(data, (int)fontStream.Length);

// close the resource stream
fontStream.Close();

// free up the unsafe memory
Marshal.FreeCoTaskMem(data);

CodingBarfield's user avatar

answered May 26, 2011 at 9:29

David Maron's user avatar

David MaronDavid Maron

1692 silver badges2 bronze badges

1

I dragged and dropped a randomly downloaded font into my resources and this worked. Uses a file though. I guess you can use this as well to install fonts ?

public Form1()
{
    string filename = @"C:lady.gaga";
    File.WriteAllBytes(filename, Resources.KBREINDEERGAMES);
    PrivateFontCollection pfc = new PrivateFontCollection();
    pfc.AddFontFile(filename);

    Label label = new Label();
    label.AutoSize = true;
    label.Font = new Font(pfc.Families[0], 16);
    label.Text = "hello world";
    Controls.Add(label);
}

answered Jul 21, 2014 at 12:12

Bitterblue's user avatar

BitterblueBitterblue

12.5k15 gold badges82 silver badges124 bronze badges

Can’t I just use the resource part of my app?

Yes, but need to be native resources rather than .NET resources (i.e. using rc.exe, the native resource compiler).

answered Feb 17, 2009 at 15:02

Richard's user avatar

RichardRichard

106k21 gold badges206 silver badges262 bronze badges

i will go with knighter’s way of embedding a font but when it comes to changing your font I choose this code:

YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

for more information: Easiest way to change font and font size

answered Aug 31, 2020 at 6:40

Jebbidan's user avatar

4

I want to embed fonts in my WinForms application so that I don’t have to worry about them being installed on the machine. I’ve searched a bit on the MSDN site and found a few hints about using native Windows API calls, for instance Michael Caplan’s (sp?) tutorial linked to by Scott Hanselman. Now, do I really have to go through all that trouble? Can’t I just use the resource part of my app?

If not I’ll probably go the installing route. In that case, can I do that programmatically? By just copying the font file to the WindowsFonts folder?

I am aware of licensing issues.

TylerH's user avatar

TylerH

20.5k62 gold badges75 silver badges97 bronze badges

asked Feb 17, 2009 at 9:59

Niklas Winde's user avatar

Niklas WindeNiklas Winde

1,7733 gold badges23 silver badges33 bronze badges

1

This is what worked for me in VS 2013, without having to use an unsafe block.

Embed the resource

  1. Double-click Resources.resx, and in the toolbar for the designer click Add Resource/Add Existing File and select your .ttf file
  2. In your solution explorer, right-click your .ttf file (now in a Resources folder) and go to Properties. Set the Build Action to «Embedded Resource»

Load the font into memory

  1. Add using System.Drawing.Text; to your Form1.cs file

  2. Add code above and inside your default constructor to create the font in memory (without using «unsafe» as other examples have shown). Below is my entire Form1.cs:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Reflection;
    
    using System.Drawing.Text;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            [System.Runtime.InteropServices.DllImport("gdi32.dll")]
            private static extern IntPtr AddFontMemResourceEx(IntPtr pbFont, uint cbFont,
                IntPtr pdv, [System.Runtime.InteropServices.In] ref uint pcFonts);
    
            private PrivateFontCollection fonts = new PrivateFontCollection();
    
            Font myFont;
    
            public Form1()
            {
                InitializeComponent();
    
                byte[] fontData = Properties.Resources.MyFontName;
                IntPtr fontPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(fontData.Length);
                System.Runtime.InteropServices.Marshal.Copy(fontData, 0, fontPtr, fontData.Length);
                uint dummy = 0;
                fonts.AddMemoryFont(fontPtr, Properties.Resources.MyFontName.Length);
                AddFontMemResourceEx(fontPtr, (uint)Properties.Resources.MyFontName.Length, IntPtr.Zero, ref dummy);
                System.Runtime.InteropServices.Marshal.FreeCoTaskMem(fontPtr);
    
                myFont = new Font(fonts.Families[0], 16.0F);
            }
        }
    }
    

Use your font

  1. Add a label to your main form, and add a load event to set the font in Form1.cs:

    private void Form1_Load(object sender, EventArgs e)
    {
        label1.Font = myFont;
    }
    

answered May 7, 2014 at 13:40

knighter's user avatar

6

// specify embedded resource name
string resource = "embedded_font.PAGAP___.TTF";

// receive resource stream
Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);

// create an unsafe memory block for the font data
System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);

// create a buffer to read in to
byte[] fontdata = new byte[fontStream.Length];

// read the font data from the resource
fontStream.Read(fontdata, 0, (int)fontStream.Length);

// copy the bytes to the unsafe memory block
Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);

// pass the font to the font collection
private_fonts.AddMemoryFont(data, (int)fontStream.Length);

// close the resource stream
fontStream.Close();

// free up the unsafe memory
Marshal.FreeCoTaskMem(data);

CodingBarfield's user avatar

answered May 26, 2011 at 9:29

David Maron's user avatar

David MaronDavid Maron

1692 silver badges2 bronze badges

1

I dragged and dropped a randomly downloaded font into my resources and this worked. Uses a file though. I guess you can use this as well to install fonts ?

public Form1()
{
    string filename = @"C:lady.gaga";
    File.WriteAllBytes(filename, Resources.KBREINDEERGAMES);
    PrivateFontCollection pfc = new PrivateFontCollection();
    pfc.AddFontFile(filename);

    Label label = new Label();
    label.AutoSize = true;
    label.Font = new Font(pfc.Families[0], 16);
    label.Text = "hello world";
    Controls.Add(label);
}

answered Jul 21, 2014 at 12:12

Bitterblue's user avatar

BitterblueBitterblue

12.5k15 gold badges82 silver badges124 bronze badges

Can’t I just use the resource part of my app?

Yes, but need to be native resources rather than .NET resources (i.e. using rc.exe, the native resource compiler).

answered Feb 17, 2009 at 15:02

Richard's user avatar

RichardRichard

106k21 gold badges206 silver badges262 bronze badges

i will go with knighter’s way of embedding a font but when it comes to changing your font I choose this code:

YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

for more information: Easiest way to change font and font size

answered Aug 31, 2020 at 6:40

Jebbidan's user avatar

4

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.

Figure 1. The Alpha Dance font file embedded in the solution.

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();

private void Form1_Load(object sender, System.EventArgs e)
{
  Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("embedfont.Alphd___.ttf");

  byte[] fontdata = new byte[fontStream.Length];
  fontStream.Read(fontdata,0,(int)fontStream.Length);
  fontStream.Close();
  unsafe
  {
    fixed(byte * pFontData = fontdata)
    {
      pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length);
    }
  }
}

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.

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
  bool bold=false;
  bool regular=false;
  bool italic=false;

  e.Graphics.PageUnit=GraphicsUnit.Point;
  SolidBrush b = new SolidBrush(Color.Black);

  float y=5;

  System.Drawing.Font fn;

  foreach(FontFamily ff in pfc.Families)
  {
    if(ff.IsStyleAvailable(FontStyle.Regular))
    {
      regular=true;
      fn=new Font(ff,18,FontStyle.Regular);
      e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
      fn.Dispose();
      y+=20;
    }
    if(ff.IsStyleAvailable(FontStyle.Bold))
    {
      bold=true;
      fn=new Font(ff,18,FontStyle.Bold);
      e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
      fn.Dispose();
      y+=20;
    }
    if(ff.IsStyleAvailable(FontStyle.Italic))
    {
      italic=true;
      fn=new Font(ff,18,FontStyle.Italic);
      e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
      fn.Dispose();
      y+=20;
    }
    if(bold  && italic)
    {
      fn=new Font(ff,18,FontStyle.Bold | FontStyle.Italic);
      e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
      fn.Dispose();
      y+=20;
    }
    fn=new Font(ff,18,FontStyle.Underline);
    e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
    fn.Dispose();
    y+=20;
    fn=new Font(ff,18,FontStyle.Strikeout);
    e.Graphics.DrawString(fn.Name,fn,b,5,y,StringFormat.GenericTypographic);
    fn.Dispose();
  }

  b.Dispose();
}

Figure 2 shows the application in action.

Figure 2. The embedded Alpha Dance font.

See the Form1_Paint event handler, it shows specifically how to set the System.Drawing.Font type. It is based on using the System.Drawing.Text.PrivateFontCollection class.

Hope this helps.

      Не секрет, что шрифтов в интернете для работы можно найти многие тысячи и на любой вкус. Инструкция поможет вам подключить сторонние шрифты к вашему приложению.
Создаем проект Windows Form в Microsoft Visual Studio и добавляем на главную форму три раза компонент «Label»



Получаем демонстрационную форму для шрифтов.



      Далее переходим в код формы, есть два способа это сделать, нажимаете клавишу «F7» или делаете клик правой клавишей мыши по форме и выбираете из контекстного меню пункт «Перейти к коду».


Если у вас все получилось, вы увидите листинг главной формы.

Для работы со шрифтами вам будет необходимо выполнить подключение следующего пространства имен:

using System.Drawing.Text;


      После выполнения указанных действий создайте рядом с исполняемым файлом программы папку «font», куда вы будете складывать все необходимые вам для работы шрифты.



Вернитесь в ваш проект и добавьте следующие два метода.

PrivateFontCollection font;
private void fontsProjects()
{
    //Добавляем шрифт из указанного файла в em.Drawing.Text.PrivateFontCollection
    this.font = new PrivateFontCollection();
    this.font.AddFontFile("font/Alice.ttf");
    this.font.AddFontFile("font/Modestina.ttf");
    this.font.AddFontFile("font/serp_and_molot.ttf");
}

private void fonts()
{
    //Задаем шрифт текста, отображаемого элементом управления.
    label1.Font = new Font(font.Families[0], 31);//Alice.ttf
    label2.Font = new Font(font.Families[1], 31);//Modestina.ttf
    label3.Font = new Font(font.Families[2], 31);//serp_and_molot.ttf
}


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

Т.е у вас получится вот такой вариант:

InitializeComponent();
//Загружаем шрифты в приложение
fontsProjects();
//Применяем шрифты к компонентам
fonts();
//Устанавливаем текст в компонентах
label1.Text = "Alice";
label2.Text = "Modestina";
label3.Text = "Серп и Молот";  

Запускаете приложение клавишей «F5» и если вы все делали по инструкции, то получите вот такой вариант:



      Если вы хотите усложнить немного данный проект, то можно реализовать меню для установки шрифтов, каждому компоненту. Добавьте два компонента «ComboBox», которые будут отвечать за выбор элемента на форме и применяемого к нему шрифта, кнопку «Button», для применения этих настроек и «NumericUpDown», для ввода размера шрифта. У вас получится вот такой вариант:


      Далее переходим к коду, сделайте двойной клик левой клавишей мыши по форме. Вы перейдете в метод «Form1_Load», который выполняется при открытии этой формы. Добавьте в него приведенный ниже листинг и получите вот такой вариант:

List list;
private void Form1_Load(object sender, EventArgs e)
{
    //Создаем список компонентов
    list = new List();            

    //Заполняем первый ComboBox именами компонентов
    foreach (Control control in Controls)
    {
        comboBox1.Items.Add(
            //Текст в компоненте
            control.Text.ToString()+", "+
            //Имя компонента
            control.Name.ToString().Replace(@"System.Windows.Forms.",""));
        //Заполняем список именами компонентов
        list.Add(control.Name.ToString().Replace(@"System.Windows.Forms.", ""));
    }
    
    //Получаем 32-разрядное целое число, представляющее общее число шрифтов
    int count = font.Families.Length;

    //Заполняем второй ComboBox именами шрифтов
    for (int j = 0; j < count; ++j)
    {
        comboBox2.Items.Add(font.Families[j].Name);
    }
}

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

(Controls[list[comboBox1.SelectedIndex]]).Font =
 new Font(font.Families[comboBox2.SelectedIndex], (int)numericUpDown1.Value);

      Запускаете приложение клавишей «F5» и если вы все делали по инструкции, то получите вот такой вариант:

141 / 53 / 11

Регистрация: 18.09.2011

Сообщений: 730

1

17.01.2012, 17:14. Показов 24605. Ответов 6


Подскажите пожалуйста, как подключить свой шрифт в свою программу в Windows Forms, чтоб этот же шрифт оставался на другом компьютере тоже, если этот шрифт не стандартный. Шрифт — имеет формат .ttf.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

17.01.2012, 17:14

Ответы с готовыми решениями:

Подключение своего шрифта
Добрый день, возник очередной вопрос к Гуру:
Допустим у меня есть свой шрифт SampleFont.ttf,…

Подключение шрифта в WPF
Добрый день.
Подскажите пожалуйста как можно подключить свои шрифты в проест.

В статье…

Создание своего шрифта.
Добрый день, у меня вопрос. В C# есть такой шрифт как WEBDINGS-шрифт в картинках. Можно ли создать…

Подключения своего шрифта
День добрый. Подскажите пожалуйста, как подключить свой шрифт к программе?
Т.е. файл &quot;.ttf&quot;?…

6

dimasamchenko

336 / 269 / 21

Регистрация: 30.03.2009

Сообщений: 500

17.01.2012, 17:49

2

Лучший ответ Сообщение было отмечено как решение

Решение

irineyxxx, очень просто. Внедрите свой шрифт в ресурсы, а затем используйте его из ресурсов.

Цитата
Сообщение от irineyxxx
Посмотреть сообщение

чтоб этот же шрифт оставался на другом компьютере тоже, если этот шрифт не стандартный

Ваш шрифт будет переносится вместе с приложением (он встроен в приложение).
Вот пример

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
   PrivateFontCollection pfc = new PrivateFontCollection();
 
 
 
    private void Form1_Load(object sender, System.EventArgs e)
 
    {
 
      Stream fontStream = this.GetType().Assembly.GetManifestResourceStream("embedfont.Alphd___.ttf");
 
 
 
      byte[] fontdata = new byte[fontStream.Length];
 
      fontStream.Read(fontdata,0,(int)fontStream.Length);
 
      fontStream.Close();
 
      unsafe
 
      {
 
        fixed(byte * pFontData = fontdata)
 
        {
 
          pfc.AddMemoryFont((System.IntPtr)pFontData,fontdata.Length);
 
        }
 
      }
 
    }

но учтите, что надо либо переделать либо использовать «In C# we can use the unsafe keyword for convienience but» из-за строки

C#
1
fixed(byte * pFontData = fontdata)

Автор кода — Bob Powell



5



Etrimus

398 / 365 / 54

Регистрация: 23.05.2010

Сообщений: 716

17.01.2012, 18:07

3

Вот так вот ещё можно, довольно просто.

C#
1
2
3
4
  System.Drawing.Text.PrivateFontCollection f = new System.Drawing.Text.PrivateFontCollection();
  f.AddFontFile("font.ttf");
 
  label1.Font = new Font(f.Families[0], 8);



3



dimasamchenko

336 / 269 / 21

Регистрация: 30.03.2009

Сообщений: 500

17.01.2012, 18:14

4

Лучший ответ Сообщение было отмечено как решение

Решение

Etrimus, У Вас фонт из файла, что подразумевает таскать файл фонта с приложением, а я предлагаю внедрить фонт в ресурсы!
Памирыч, раз Вы заинтересовались то предлагаю кусочек своего кода, как я делал для себя

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Resources;
using System.Runtime.InteropServices;
using System.Drawing.Text;
 
 
namespace MusicFont
  {
  public partial class Form1 : Form
    {
    //=============================================================
  
   private Font OldFont;
 
  Font myFont;
  PrivateFontCollection private_fonts = new PrivateFontCollection();
   //=============================================================
    public Form1()
      {
      InitializeComponent();
      LoadFont();
      label1.Font = new Font(private_fonts.Families[0], 22);
      label1.UseCompatibleTextRendering = true;
      }
//=============================================================
    private void LoadFont()
      {
   
      using (MemoryStream fontStream = new MemoryStream(Properties.Resources.MusiQwik))
        {
        // create an unsafe memory block for the font data
        System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
        // create a buffer to read in to
        byte[] fontdata = new byte[fontStream.Length];
        // read the font data from the resource
        fontStream.Read(fontdata, 0, (int)fontStream.Length);
        // copy the bytes to the unsafe memory block
        Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);
        // pass the font to the font collection
        private_fonts.AddMemoryFont(data, (int)fontStream.Length);
        // close the resource stream
        fontStream.Close();
        // free the unsafe memory
        Marshal.FreeCoTaskMem(data);
 
        }
     
      }
    //=============================================================
    private void button1_Click(object sender, EventArgs e)
      {
 
 
      label1.Text = "&=B=C=D=E=F=G=H=I=!=R=S=T=U=!";
 
      }
    //=============================================================
    private void button2_Click(object sender, EventArgs e)
      {
 
              }
    //=============================================================
    }
  }

MusiQwik — это имя шрифта
в результате в лабел рисуются ноты



7



npocma4ok

0 / 0 / 0

Регистрация: 17.07.2012

Сообщений: 5

30.07.2012, 20:04

5

Цитата
Сообщение от dimasamchenko
Посмотреть сообщение

Etrimus, У Вас фонт из файла, что подразумевает таскать файл фонта с приложением, а я предлагаю внедрить фонт в ресурсы!
Памирыч, раз Вы заинтересовались то предлагаю кусочек своего кода, как я делал для себя

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Resources;
using System.Runtime.InteropServices;
using System.Drawing.Text;
 
 
namespace MusicFont
  {
  public partial class Form1 : Form
    {
    //=============================================================
  
   private Font OldFont;
 
  Font myFont;
  PrivateFontCollection private_fonts = new PrivateFontCollection();
   //=============================================================
    public Form1()
      {
      InitializeComponent();
      LoadFont();
      label1.Font = new Font(private_fonts.Families[0], 22);
      label1.UseCompatibleTextRendering = true;
      }
//=============================================================
    private void LoadFont()
      {
   
      using (MemoryStream fontStream = new MemoryStream(Properties.Resources.MusiQwik))
        {
        // create an unsafe memory block for the font data
        System.IntPtr data = Marshal.AllocCoTaskMem((int)fontStream.Length);
        // create a buffer to read in to
        byte[] fontdata = new byte[fontStream.Length];
        // read the font data from the resource
        fontStream.Read(fontdata, 0, (int)fontStream.Length);
        // copy the bytes to the unsafe memory block
        Marshal.Copy(fontdata, 0, data, (int)fontStream.Length);
        // pass the font to the font collection
        private_fonts.AddMemoryFont(data, (int)fontStream.Length);
        // close the resource stream
        fontStream.Close();
        // free the unsafe memory
        Marshal.FreeCoTaskMem(data);
 
        }
     
      }
    //=============================================================
    private void button1_Click(object sender, EventArgs e)
      {
 
 
      label1.Text = "&=B=C=D=E=F=G=H=I=!=R=S=T=U=!";
 
      }
    //=============================================================
    private void button2_Click(object sender, EventArgs e)
      {
 
              }
    //=============================================================
    }
  }

MusiQwik — это имя шрифта
в результате в лабел рисуются ноты

Не совсем разобрался с подключением нескольких своих шрифтов. Точнее в моей программе используется один шрифт. Но я использую болд и регуляр — так вот. один шрифт подключился и все ок. А вот со вторым не могу разобраться.



0



64 / 49 / 7

Регистрация: 09.11.2012

Сообщений: 219

25.01.2013, 16:23

6

dimasamchenko, скинул другу, у него показывает стандартный какой-то шрифт. Что-то не так…



0



yariko

14 / 11 / 6

Регистрация: 28.11.2016

Сообщений: 58

Записей в блоге: 8

01.06.2019, 06:27

7

dimasamchenko,
Спасибо за решение. Тоже искал инфу как подключить шрифт. Данный вариант очень помог.

Однако думаю что код можно немного упростить отключив строку fontStream.Close()

C#
1
2
3
4
5
6
using (MemoryStream fontStream = new MemoryStream(Properties.Resources.MusiQwik))
{
...
//close the resource stream
//fontStream.Close();
}

Ведь известно, что оператор using заранее подразумевает освобождение обьекта при выходе за пределы фигурных скобок. Поэтому необходимости вызывать Close() внутри using отсутствует.



0



Constructor. This example is a Windows Forms program and its uses the simplest Font constructor. We specify a font name («Times New Roman») as the first argument. The second argument is of type float and specifies the size.

Tip: If you get an error about the number format of the second argument, use the «f» suffix to specify that the number should be a float.

Suffixes

Example that creates Font instance: C#

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

Font

font = new Font(«Times New Roman», 12.0f);

// Set Font property and then add a new Label.
this.Font = font;
this.Controls.Add(new Label() { Text = «The Dev Codes» });
this.Size = new Size(300, 200);
}
}
}

FontStyle, FontFamily. Next we demonstrate a more complex constructor. We introduce the FontFamily type. This type describes a specific family of fonts, such as the «Times New Roman» family. No style, size, or other information is part of the FontFamily.

Info: In the Font constructor, we specify the FontStyle using the bitwise OR operator. This is used on enums with the [Flags] attribute.

Result: The program renders a Label with «Times New Roman» that is bold, italic, and underlined at 16 points.

Enum Flags

Example that uses another Font constructor: C#

using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

FontFamily

family = new FontFamily(«Times New Roman»);

Font

font = new Font(family, 16.0f,
FontStyle.Bold | FontStyle.Italic | FontStyle.Underline);

// Set Font property.
this.Font = font;
this.Controls.Add(new Label() { Text = «The Dev Codes», Width = 250 });
this.Size = new Size(300, 200);
}
}
}

Bold, Italic, Underline. The Font type also provides the properties Bold, Italic, and Underline. These properties are read-only. You can access them to determine the styles set on the Font, but can’t change the styles. You must instead use the Font constructor.

Font.Style. The Style property on the Font type is also read-only. It will tell you what styles are set on the Font instance, but you cannot mutate them. Instead, you can create a new Font with the constructor.

Font exists. Some fonts don’t exist on some systems. We develop code that chooses the best font for a program. Windows Forms has an interesting behavior with the Font object when the font doesn’t exist on the system.

And: It will simply not create the new font at all. Thus you can check whether that happened to see if the font exists.

SetFontFinal: This method uses logic for font existence testing. The font is «Cambria,» which is only present on recent versions of windows.

Name: After we make the new Font object, we can test the Name property on it. If the name «Cambria» is still set, the font exists.

But: If the Name property is not the same as specified, the font doesn’t exist. In this case we another font.

C# program that uses Font objects

public partial class Form1 : Form
{
public Form1()
{
SetFontFinal();
InitializeComponent();
}

private void SetFontFinal()
{
string fontName = «Cambria»;
Font testFont = new Font(fontName, 16.0f, FontStyle.Regular,
GraphicsUnit.Pixel);

if (testFont.Name == fontName)
{
// The font exists, so use it.
this.Font = testFont;
}
else
{
// The font we tested doesn’t exist, so fallback to Times.
this.Font = new Font(«Times New Roman», 16.0f,
FontStyle.Regular, GraphicsUnit.Pixel);
}
}
}

Summary. The Font type is useful in graphical programs in the .NET Framework and C# language. It cannot represent colors of fonts, but it does store information about styles, sizes and typefaces.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace WindowsFormsApp8 {

public partial class Form1 : Form {

    public Form1()

    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)

    {

        Label l = new Label();

        l.AutoSize = true;

        l.Text = "Do you want to submit this form?";

        l.Location = new Point(222, 145);

        l.Font = new Font("French Script MT", 18);

        this.Controls.Add(l);

        Button Mybutton = new Button();

        Mybutton.Location = new Point(225, 198);

        Mybutton.Text = "Submit";

        Mybutton.AutoSize = true;

        Mybutton.BackColor = Color.LightBlue;

        Mybutton.Padding = new Padding(6);

        Mybutton.Font = new Font("French Script MT", 18);

        this.Controls.Add(Mybutton);

        Button Mybutton1 = new Button();

        Mybutton1.Location = new Point(438, 198);

        Mybutton1.Text = "Cancel";

        Mybutton1.AutoSize = true;

        Mybutton1.BackColor = Color.LightPink;

        Mybutton1.Padding = new Padding(6);

        Mybutton1.Font = new Font("French Script MT", 18);

        this.Controls.Add(Mybutton1);

    }

}

}

Понравилась статья? Поделить с друзьями:
  • Как добавить шрифт в paint windows 7
  • Как добавить шрифт в libreoffice в windows
  • Как добавить шрифт в inkscape windows
  • Как добавить шрифт в adobe acrobat pro windows 10
  • Как добавить шрифт ttf в windows 10