Using an embedded resource font in Visual Studio VB 2022 - vb.net

I have been trying (without success) to use and embedded font in my VB project. I have done it before but now I can't remember how to do it. I have been searching and searching on here and other websites, but stuff I have tried isn't working.
This is the only way I can do it at the moment. It works but I want to embed the font.
Dim privateFonts As New System.Drawing.Text.PrivateFontCollection()
privateFonts.AddFontFile("D:\somefont.ttf")
Dim font As New System.Drawing.Font(privateFonts.Families(0), 12)
Label1.Font = font
I have embedded the font no problem.
What code do I need to pull the font from the resource file and use it, on a label or panel, for example.
I know this has been asked so many times before, but nothing I try is working.
Thanks (with some embarrassment) in advance.
Neil.

I found a working solution on another site.
Imports System.Runtime.InteropServices
Public Class Form1
Public privateFontCollection As New Drawing.Text.PrivateFontCollection
Public FamilyName As String
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
Dim data As System.IntPtr = Marshal.AllocCoTaskMem(My.Resources.amstrad_cpc464.Length - 1)
Marshal.Copy(My.Resources.amstrad_cpc464, 0, data, My.Resources.amstrad_cpc464.Length)
privateFontCollection.AddMemoryFont(data, My.Resources.amstrad_cpc464.Length)
Marshal.FreeCoTaskMem(data)
Dim fnt As Font = New Font(privateFontCollection.Families(0), 15)
Label1.Font = fnt
End Sub
End Class

Related

VB.Net VLC Player documented usage not quite working

I'm trying to use the VlcDotNet library to embed a small media player into a VB.Net forms-based project.
Mainly I'm following the solution that I found here:
Display video with VlcDotNet library
except that I've had to translate from C# to VB.
Having followed the instructions to the letter, there are two lines of the code which simply aren't recognised and won't compile. Certain methods of the Vlc.DotNet.Core code simply aren't accepted as valid.
Having used NuGet to get 4 Vlc.DotNet packages (.Core, .Core.Interops, .Forms and .Wpf), my complete code (excluding the very basic design of one button and one panel) is below. The compiler won't compile it, because it says there are 2 errors.
Firstly, "Type Vlc.DotNet.Core.Medias.MediaBase is not defined" (for the 'Dim newMedia as...' line)
Secondly, "'Media' is not a member of 'Vlc.DotNet.Forms.Control" (for the '.Media = newMedia' line)
Almost all the methods of the VlcControl are present, but I can't see why certain elements, such as the Media method, are simply not there?
Any suggestions would be extremely welcome.
Thanks
Imports Vlc.DotNet.Core
Imports Vlc.DotNet.Core.Interops
Imports Vlc.DotNet.Forms
Imports Vlc.DotNet.Wpf
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim player As New Vlc.DotNet.Forms.VlcControl
Panel1.Controls.Add(player)
With player
.BackColor = Color.Blue
.ImeMode = Windows.Forms.ImeMode.NoControl
.Location = New System.Drawing.Point(0, 0)
.Name = "test"
.Rate = 0.0F
.Size = Panel1.Size
Dim newMedia As Vlc.DotNet.Core.Medias.MediaBase = New Vlc.DotNet.Core.Medias.PathMedia("E:\TempTest.mov")
.Media = newMedia
.Play()
End With
End Sub
End Class
I had try to convert out from C# and below are the new library files using method:
Public myvlc As New VlcControl
myvlc.Dock = DockStyle.None
myvlc.Size = New Size(myscreen.Bounds.Width, myscreen.Bounds.Height)
myvlc.Location = New Point(0, 0)
Me.Controls.Add(myvlc)
AddHandler myvlc.VlcLibDirectoryNeeded, AddressOf LibNeeded
Private Sub LibNeeded(ByVal Sender As Object, ByVal e As VlcLibDirectoryNeededEventArgs)
e.VlcLibDirectory = New IO.DirectoryInfo("C:\lib\x86\")
End Sub
Please download the Video Codec lib from the same website where you get the vlc.dotnet.

Using animated gif in splash screen vb.net

I'm having trouble creating a .gif be animated in my already created visual studio 2013 project.
Been looking online a bit for the "proper" way to do it. Following this MSDN question: Link I copied some of the code to see how it would work. I've also seen references to using a timer.
Public Not Inheritable Class SplashScreen
Private progressGifPath As String = "C:\Documents\Visual Studio 2013\Projects\CameraFinder\icons" + "\orangeLoading.gif"
Private _AnimatedGif As New Bitmap(progressGifPath)
Private m_IsAnimating As Boolean
Public Property IsAnimating() As Boolean
Get
Return m_IsAnimating
End Get
Set(ByVal value As Boolean)
m_IsAnimating = value
End Set
End Property
Private Sub VICameraFinderLoading_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Set up the dialog text at runtime according to the application's assembly information.
If My.Application.Info.Title <> "" Then
Else
End If
End Sub
Private Sub PlayGIF()
If Not m_IsAnimating Then
ImageAnimator.Animate(_AnimatedGif, New EventHandler(AddressOf Me.OnFrameChanged))
m_IsAnimating = True
End If
End Sub
Private Sub OnFrameChanged(ByVal o As Object, ByVal e As EventArgs)
If m_IsAnimating Then
ImageAnimator.UpdateFrames()
Dim aGraphics As Graphics = PictureBox.CreateGraphics
aGraphics.DrawImage(_AnimatedGif, New Point(30, 30))
aGraphics.Dispose()
End If
End Sub
End Class
So I tried this, but I don't see anything on the picture box drawn (I confirmed to see it was brought to the front). And apparently there can be a size limit to the gif included. Any ideas on what would be the better way to include it?
Thanks!
Figured it out. I hadn't set the image of the picture box to the gif.
EDIT:
To clarify, the code above wasn't the problem at all. I actually didn't need it in any way. I removed it from the splash screen class, completely. The solution was to go into my picture box's property (F4) and set the backgroundImage to the .gif's filepath (thus importing it as an embedded resource). Doing so has allowed for animation in the splash screen.

How do I use a font not installed in my computer in Visual Basic?

How do I use a font not installed in my computer in Visual Basic and the font file is in my resources?
I tried this but I guess it only works when the file is not on the resources.
Imports System.Drawing.Text
Public Class frmTitle
Private Sub frmTitle_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim myFont As New PrivateFontCollection()
myFont.AddFontFile(My.Resources.font_space_invaders)
lblPressStart.Font = New Font(myFont.Families(0), 20, FontStyle.Bold)
End Sub
End Class
How about trying like this:-
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("C:\\Path To\\PALETX3.ttf");
label1.Font = new Font(pfc.Families[0], 16, FontStyle.Regular);

Pressing a button in visual basic

I am new to Visual Basic.NET and I am just playing around with it. I have a book that tells me how to read from a file but not how to write to the file with a button click. All I have is a button and a textbox named fullNameBox. When I click the button it gives me an unhandled exception error. Here is my code:
Public Class Form1
Sub outputFile()
Dim oWrite As System.IO.StreamWriter
oWrite = System.IO.File.CreateText("C:\sample.txt")
oWrite.WriteLine(fullNameBox.Text)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
outputFile()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Have you tried stepping through your application to see where the error is? With a quick glance, it looks like you might need to use System.IO.File on the fourth line (oWrite = IO.File...) instead of just IO, but I haven't tried to run it.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(SaveFileDialog1.FileName.Trim, FileMode.Create)
Dim sr As New StreamWriter(fs)
sr.Write(TextBox1.Text)
fs.Flush()
sr.Close()
fs.Close()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(OpenFileDialog1.FileName.Trim, FileMode.Open)
Dim sw As New StreamReader(fs)
TextBox1.Text = sw.ReadToEnd
fs.Flush()
sw.Close()
fs.Close()
End If
End Sub
End Class
this is a complete functional program if you want, you just need to drag drop a textbox, openfiledialog, and a savefiledialog.
feel free to play around with the code.
enjoy
by the way, the problem in your code is that you "must" close filestream when your done using it, doing so will release any resource such as sockets and file handles.
The .net framework is a very powerful framework. In the same way (however) it has easy and convenient methods for simple tasks. Most individuals tend to complicate things in order to display knowledge. But less code = less processing = faster and more efficient application (sometimes) so the large above method may not be suitable. Along with that, the above mentioned method would be better off written as a sub or if returning something then a function.
My.Computer.FileSystem.WriteAllText("File As String", "TextAsString", Append as Boolean)
A general Example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", "this is what I would like to add", False)
this is what I would like to add
can be changed to the current text of a field as well.
so a more specific example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", fullNameBox.text, True)
If you would like to understand the append part of the code
By setting append = true you are allowing your application to write the text at the end of file, leaving the rest of the text already in the file intact.
By setting append = false you will be removing and replacing all the text in the existing file with the new text
If you don't feel like writing that part of the code (though it is small) you could create a sub to handle it, however that method would be slightly different, just for etiquette. functionality would remain similar. (Using StreamWriter)
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", append as boolean)
objWriter.WriteLine(textboxname.Text)
objWriter.Close()
End Sub
The Specific Example would be
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", False)
objWriter.WriteLine(fullnamebox.Text)
objWriter.Close()
End Sub
then under the button_click event call:
writetext()
You can take this a step further as well. If you would like to create a more advabced Sub to handle any textbox and file.
Lets say you plan on having multiple separate files and multiple fields for each file (though there is a MUCH cleaner more elegant method) you could create a function. {i'll explain the concept behind the function as thoroughly as possible for this example}
below is a more advanced sub demonstration for your above request
Private Sub WriteText(Filename As String, app As Boolean, text As String)
Dim objWriter As New System.IO.StreamWriter(Filename, app)
objWriter.WriteLine(text)
objWriter.Close()
End Sub
What this does is allows us to (on the same form - if you need it global we can discuss that another time, it's not much more complex at all) call the function and input the information as needed.
Sub Use -> General Sample
WriteText(Filename As String, app As Boolean)
Sub Use -> Specific Sample
WriteText("C:\text.txt, False, fullnamebox.text)
But the best part about this method is you can change that to be anything as you need it.
Let's say you have Two Buttons* and **Two Boxes you can have the button_event for the first button trigger the above code and the second button trigger a different code.
Example
WriteText("C:\text2.txt, False, halfnamebox.text)
The best part about creating your own functions and subs are Control I won't get into it, because it will be off topic, but you could check to be sure the textbox has text first before writing the file. This will protect the files integrity.
Hope this helps!
Richard Sites.

How can I embed font in Visual Basic .Net application?

How can I embed font in Visual Basic .Net application? which should valid at every operating system.
It is possible to embed a font in an application and use it if that font is not available on the user's system.
You simply create a PrivateFontCollection and populate it with your fonts then you can use them as you please. According to MSDN, this method does not apply to operating systems before Windows 2000.
From Remarks section of PrivateFontCollection.AddFontFile method:
When using a private font on operating systems before Windows 2000, the default font, typically Microsoft Sans Serif, will be substituted.
If you intend your application to be used on Windows 2000 and newer, you can follow this code I wrote to see how to implement private fonts.
Public Class Form1
Dim pfc As System.Drawing.Text.PrivateFontCollection
Dim ifc As System.Drawing.Text.InstalledFontCollection
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
pfc = New System.Drawing.Text.PrivateFontCollection()
ifc = New System.Drawing.Text.InstalledFontCollection()
LoadPrivateFonts({My.Resources.Series_60_ZDigi, My.Resources.Times_NR_Phonetics_2})
End Sub
''' <summary>Loads the private fonts.</summary>
''' <param name="fonts">The fonts to be loaded into the private font collection.</param>
Private Sub LoadPrivateFonts(ByVal fonts As IEnumerable(Of Byte()))
For Each resFont In fonts
pfc.AddMemoryFont(Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(resFont, 0), resFont.Length)
Next
End Sub
''' <summary>Gets the FontFamily whose name matches the one specified.</summary>
''' <param name="fontName">Name of the FontFamily to be returned.</param>
''' <param name="defaultFamily">
''' Optional. The default font family to be returned if the specified font is not found
''' </param>
Private Function GetFontFamily(ByVal fontName As String, Optional ByVal defaultFamily As FontFamily = Nothing) As FontFamily
If String.IsNullOrEmpty(fontName) Then
Throw New ArgumentNullException("fontName", "The name of the font cannont be null.")
End If
Dim foundFonts = From font In ifc.Families.Union(pfc.Families) Where font.Name.ToLower() = fontName.ToLower()
If foundFonts.Any() Then
Return foundFonts.First()
Else
Return If(defaultFamily, FontFamily.GenericSansSerif)
End If
End Function
Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
'free the resources used by the font collections
pfc.Dispose()
ifc.Dispose()
End Sub
Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
Dim g = e.Graphics
Using br As Brush = Brushes.Black
g.DrawString("1234567890ABCDEF", New Font(GetFontFamily("Series 60 ZDigi"), 18), br, New Point(20, 20))
g.DrawString("ABCDEFGHIJKLMNOP", New Font(GetFontFamily("Times NR Phonetics 2"), 18), br, New Point(20, 100))
End Using
End Sub
End Class
I load the two fonts I use in the application (Series 60 ZDigi, a font from my Nokia phone, and Times NR Phonetics 2, a font from my dictionary application) from the resources into the private font collection in the Sub New().
I then call the GetFontFamily method to get the desired font to paint onto the form.
It shouldn't be too hard to incorporate this into your applications.
Cheers.
You can't. There is no cross-platform standard at this point for embedded fonts in a standard Winforms application. The best you can do is embed individual, OS-specific font files, detect which OS you're on, and then install the font programmatically.
On the other hand, A WPF application in VB.net might work for your needs, but I have a feeling this isn't where you're going. For information on how to package fonts with a WPF application, see this MSDN article.