0

I saved my downloaded font in resources and want it to be set on certain checkbox whenever the program is loaded.

I've already tried this:

Checkbox1.Font = My.Resources.Allstar

("Allstar" is the name of the font ofc)

but it gives me an error:

Value of type '1-dimensional array of Byte' cannot be converted to 'System.Drawing.Font)

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151

1 Answers1

3

Load the resource into a PrivateFontCollection object. Something like this should be close:

    Dim lstPrivateFontCollection As New System.Drawing.Text.PrivateFontCollection

    Dim objPointer As IntPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(My.Resources.Allstar.length)

    System.Runtime.InteropServices.Marshal.Copy(My.Resources.Allstar, 0, objPointer, My.Resources.Allstar.Length)

    lstPrivateFontCollection.AddMemoryFont(objPointer, My.Resources.Allstar.Length)

    'Omit next line due to instability pointed out in comments by Hans Passant.
    'It was used to free memory, but could cause app to crash.
    'System.Runtime.InteropServices.Marshal.FreeCoTaskMem(objPointer)

    Dim objFont As New System.Drawing.Font(lstPrivateFontCollection.Families(0), 16.0F, System.Drawing.FontStyle.Regular, GraphicsUnit.Point)

    lstPrivateFontCollection.Dispose()

    Checkbox1.Font = objFont
NoAlias
  • 9,218
  • 2
  • 27
  • 46
  • 1
    It freaking works! I only had to put your code in my form_load. THANK YOU SO MUCH!!! – Mordehaj Bukarej Nov 27 '13 at 20:54
  • It doesn't, the FreeCoTaskMem() call will randomly crash your program. It must not be made until the font can no longer be used. – Hans Passant Nov 27 '13 at 20:55
  • I meant it is working when I change my Checkbox font to some random one and it automatically changes back to Allstar without any errors. Now I am sending exe to my friend so maybe it works for him too. – Mordehaj Bukarej Nov 27 '13 at 21:00
  • Thanks for the warning on the FreeCoTaskMem() @HansPassant – NoAlias Nov 27 '13 at 21:03
  • Yep, so @HansPassant was right. It doesn't work for my friend as he doesn't have this font. – Mordehaj Bukarej Nov 27 '13 at 21:08
  • It should come through as an embedded resource. If you sent him just the code without the resource it won't work. The FreeCoTaskMem() should not be called where I originally had it though due to possible instabilities. – NoAlias Nov 27 '13 at 21:11
  • So how to do it so he can see the font? I have to send him the .ttf file and he has to put it in control panel>fonts or is there an easier way? I thought the resource thing stores things that are loaded when you run the exe. Now I'm confused :/ The weird thing is that it works good with images, I mean I have 2 images in resources and he can see without having them on drive. How is this working? – Mordehaj Bukarej Nov 27 '13 at 21:24