PowerBuilder – Add /Remove a Font at Runtime

Posted on Wednesday, January 12th, 2011 at 8:20 pm in

Here is a way to add (and remove) a font to the user’s machine at runtime. You can also use this to check if a user has a particular font installed since the code also shows how to list all the installed fonts (need MS Word for this). Way back in my PB5 days I coded a process to print checks. Rather than fool with preprinted forms this application printed all of the data to produce a check which could be processed by banks just like any other. The printer would have to use special magnetic ink and we also used a special MICR font for the bank routing and account numbers. Although the application never really made it into the ‘real’ world, I always thought the potential for fraud was significant. If the font were dynamically added and removed from the workstation, this potential would have been somewhat less.

The basic process makes use of two windows API calls: AddFontResource and RemoveFontResource. The declarations are as follows (both ANSI and Unicode):

Function int AddFontResourceA(string lpFileName) library "gdi32.dll"
Function int AddFontResourceW(string lpFileName) library "gdi32.dll"
Function int RemoveFontResourceA(string lpFileName) library "gdi32.dll"
Function int RemoveFontResourceW(string lpFileName) library "gdi32.dll"

To demonstrate the techniques, I’ve created a sample application.

In the ‘Load Fonts’ button clicked event there is the following:

integer li_fonts, li_i
long	ll_row
OLEObject lole_word, lole_fonts
string ls_file_name
dw_1.reset() // clear existing entries

lole_word = CREATE oleobject
lole_fonts = CREATE oleobject
TRY
	lole_word.connecttonewobject('word.application')
CATCH (runtimeerror a)
	Messagebox('Error','Error connecting with MS Word. Process terminating.')
	RETURN -1
END TRY
lole_word.visible = FALSE // dont want to see word
lole_fonts = lole_word.fontnames
li_fonts = lole_fonts.count
// build font list in datawindow
FOR li_i = 1 to li_fonts
	ll_row = dw_1.insertrow(0)
	dw_1.setitem(ll_row,'fontname',lole_fonts.item(li_i))
NEXT
dw_1.sort()
lole_word.quit() // close word
DESTROY lole_fonts
DESTROY lole_word

This uses OLE with MS Word to retrieve the list of font names installed on the system.

There is a font file included with the example which can be used as the temporary font in the demonstration. Run the application and click on the ‘Select Font File’ button to choose this file.

Now click the ‘Add Font’ button. The font’s name and a sample of it should appear in the appropriate fields.

If you click the ‘Load Fonts’ button again you will see the new font name in the list.

Finally, click the ‘Remove Font’ button to remove it. The ‘New Font Example’ text will now revert.

If you click the ‘Load Fonts’ button again you will see the new font name has been removed from the list.

The zip archive containing the PB files, exports, and the sample font file can be downloaded here.

Top