Convert string to system font

daverage

Active member
Joined
Aug 29, 2006
Messages
26
Programming Experience
Beginner
Is it possible to convert this string
[Font: Name=Microsoft Sans Serif, Size=8.25, Units=3, GdiCharSet=0, GdiVerticalFont=False]

into a system font

Basically i am saving the font details as a string then wanting to recall them.
 
This is all about serialization, and since a font can be serialized and de-serialized it's just a matter of doing the conversion. Found this snippet that does all the leg work for you. This little class also utilises generics, which means you can serialize anything with it.

VB.NET:
Friend Class SerializeSomething (Of T)
 
 
Friend Function SerializeFontObject(ByVal oObject As T) As [URL="http://www.dotnet247.com/247reference/System/String.aspx"]String[/URL]
    Dim bf As New [URL="http://www.dotnet247.com/247reference/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.aspx"]BinaryFormatter[/URL]
Dim mem As New [URL="http://www.dotnet247.com/247reference/System/IO/MemoryStream.aspx"]MemoryStream[/URL]
 
    Try
     bf.Serialize(mem, oObject)
    Return [URL="http://www.dotnet247.com/247reference/System/Convert.aspx"]Convert[/URL].ToBase64String(mem.ToArray())
    Catch
        Return [URL="http://www.dotnet247.com/247reference/System/String.aspx"]String[/URL].Empty
    Finally
     mem.Close()
    End Try
End Function    
 
Friend Function DeserializeFontObject(ByVal sString As String) As T
    Dim bf As New [URL="http://www.dotnet247.com/247reference/System/Runtime/Serialization/Formatters/Binary/BinaryFormatter.aspx"]BinaryFormatter[/URL]
    Dim mem As New [URL="http://www.dotnet247.com/247reference/System/IO/MemoryStream.aspx"]MemoryStream[/URL]([URL="http://www.dotnet247.com/247reference/System/Convert.aspx"]Convert[/URL].FromBase64String(sString))
 
    Try
        Return DirectCast(bf.Deserialize(mem), T)
    Finally
        If Not mem Is Nothing Then
            mem.Close()
        End If
    End Try
 
End Function
End class
 
Ok, that works great but is not ideal as i want the results to be readable in my xml!!
Can i use these settings to change the font of a text area?

<Name>Microsoft Sans Serif</Name>
<GdiCharSet>0</GdiCharSet>
<Strikeout>False</Strikeout>
<Style>0</Style>
<Underline>False</Underline>
<Bold>False</Bold>
<Italic>False</Italic>
<Size>8.25</Size>
 
It probably is possible, but why is it important to have the serialized data readable?. XML isn't particularly readable anyway, when comapred to a text file.
 
mmm, ok. Well give this a try. You may need to play with it a bit...

VB.NET:
'Font To String....
 
Dim tc As TypeConverter = TypeDescriptor.GetConverter(GetType(Font))
Dim fontString As String = tc.ConvertToString(font)
 
 
'String To Font....
 
Dim newFont As Font = CType(tc.ConvertFromString(fontString), Font)

Uses the type converter already built into the framework, much less code to write and should be just as effective.
 
Back
Top