Post History
This library was first released on the original AutoHotkey forum. You can find the original post here.
Introduction
Most font requirements can be handled with the AutoHotkey gui Font and GUIControl Font commands but there are limitations. The Fnt library was created to expand on what can be done with fonts.
Fnt Library
Key features:
Create fonts. Create and delete logical fonts as needed. Yes, this is one way to get around the AutoHotkey upper limit of 200 fonts. Starting with v0.6, creating any of the standard non-client fonts (Ex: Menu font) is a snap.
Calculate the size of GUI controls before creating them. Or after changing the font of a GUI control. New functions introduced in v3.0 make it even easier to accurately calculate the size for some GUI controls.
Calculate the tab stops on Edit, Rich Edit, or ListBox controls. New functions released in v0.6 make it much easier to set the tab stops based on actual data.
Calculate the largest font size to fit. A new function released in v4.0 makes it easy to calculate the font size needed to fit text within a fixed space.
What's New in Version 4
Version 4 is not a reboot but there are a large number of changes and a large number of possible script breakers. Please read the Release Notes carefully before using. Some key updates:
New functions:
Fnt_CalculateFontSizeToFit. Calculate the font size needed to fit a string of one or lines of text to fit within a fixed space. Version 3.0 of the library included a experimental version of a function that did something similar. This function is significantly more efficient.
Fnt_DrawText and Fnt_DrawTextToBitmap. These functions include a large number of formatting options to draw text to a static control or to a bitmap.
Fnt_IsValidFaceName and Fnt_IsValidFontName. Quickly determine if a font is installed on the current computer.
Character set. New functions and changes to existing functions to support the character set of a font.
Updates:
Flag/Option string names. All functions with parameters that contain bit flag values have been modified to also support string names that represent each bit flag value. For example, instead of setting a parameter to the following bit flag values: 0x800|0x40000|0x2000000, a string with the following values can be used instead: "NoOEMFonts|TTOnly|InactiveFonts". This update makes it significantly easier to set the flag values, make changes, and to debug.
Fnt_ChooseFontDlg. This function has been modified so that it no longer requires non-Fnt functions to operate. Interpretation: All external functions have been integrated into the Fnt library.
Documentation. The general library documentation has been moved to the _Fnt.Doc.ahk file. Natural Docs v2.0 is used to generate HTML documentation from this file and from the function documentation. This HTML document is in a new format that is different from the previous version of this library. See the Release Notes for more information.
The Code
The pertinent files are as follows:
Project: Fnt.zip
This archive file includes Fnt library, add-on libraries, example scripts, and project documentation.
Documentation: Starting with v4.0, the project documentation is included in the project archive file (above).
Compatibility
Starting with v2.0, this library is designed to work on all versions of AutoHotkey v1.1+. It is not compatible with AutoHotkey v2.0+.
Issues/Considerations
A few considerations:
Windows compatibility. The library is designed to run on all versions of Windows >= Windows Vista. The reality is that I only have one machine to test this software on. If you experience any problems with your version of Windows, please let me know. I will try to correct the problem.
DPIScale. The DPIScale feature (AutoHotkey v1.1.11+) can be incompatible with the Fnt library. See the library documentation for more information.
Tooltips. Out of the blue, Microsoft changed how the tooltip control responds to certain messages. The tooltip may no longer automatically redraw when the WM_SETFONT message is sent. Worse yet, if the Redraw option of the WM_SETFONT message is set to TRUE, the tooltip may be deactivated (hidden but not destroyed). Starting with v0.9, the Fnt_UpdateTooltip function was added to work in conjunction with the Fnt_SetFont function when used on a tooltip control. See the documentation in the Fnt_SetFont function for more information.
Windows 10+. There are a very small number of features that work as expected on Windows XP through Windows 7, but do not work as expected on Windows 10+. They are certainly not show stoppers but the "inconvenience factor" may be consideration. These "works differently on Windows 10" issues are identified in the release notes or in the project documentation.
Examples. If any of the examples don't work as expected, please let me know. I will try to correct the problem. Also, the examples have been written for the most common screen resolutions - 1920x1080 or higher. Screens with resolutions at least 1280x768 should work fine but there might be a few exceptions. For screens with a resolution less than 1280x768, there may be more than than a few examples that don't display well. If you experience a problem with an example because of screen resolution, let me know. I will try to correct the problem.
Last AutoHotkey v1.1+ Version
With the exception of bug fixes, v4.0 will be last version of the Fnt library for AutoHotkey v1.1+. Future versions (if any) will require AutoHotkey v2.0+.
v4.0
This is a major release with new functions and many changes. Please read these release notes carefully before using.
Bug fixes:
• Fnt_GetListOfFonts. Fixed so that the callback function is not registered every time the function is called. This change stops the function from generating a small memory leak (32 bytes plus system overhead) for the 2nd and subsequent calls to the function.
Updates/Enhancements:
• Fnt_CalculateSize. The ByRef r_Text parameter changed to p_Text, a standard parameter. This parameter no longer has to be variable and if a variable is passed, the variable is not updated if the DT_MODIFYSTRING format and other conditions cause the text to modified after calling this function. This change was made so the developer can use the same string to measure the text and then use it for other reasons. The modified string (if any) is now returned as a property of the return object (new in v4.0).
• Fnt_ChooseFont. There are several updates/enhancements. 1) Enhanced so that string values can be used in the p_Flags parameters (Ex: "FixedPitchOnly") and can contain multiple values (Ex: "TTOnly|FixedPitchOnly|NoVertFonts"). See the function documentation for more information. 2) Added support for the CF_INACTIVEFONTS flag. If this flag is included, hidden fonts will be included in the list of fonts (Windows 7+). 3) Additional information including a LOGFONT structure is returned if a font is selected. See the function documentation for more information.
• Fnt_ChooseFontDlg. There are several updates/enhancements. 1) Enhanced so that string values can be used in the p_Effects and p_Flags parameters (Ex: "TypeFace") and can contain multiple values (Ex: "TypeFace|Size|Style"). See the function documentation for more information.2) Added support for the CF_INACTIVEFONTS flag. If this flag is included, hidden fonts will be included in the list of fonts (Windows 7+). 3) Added support for a new custom flag, CF_RASTERONLY. If this flag is included, only raster (binary) fonts are included in the list of fonts. 4) Additional information is returned if a font is selected. See the function documentation for more information.
• Fnt_GetAverageCharWidth. Updated so that the default GUI font is used if the hFont parameter is 0, null, or is not specified.
• Fnt_GetListOfFonts. There are several updates/enhancements. 1) The p_Flags parameter has been enhanced so that flag "name" strings can be specified instead of flag values. Ex: "NoOEMFonts". See the function documentation for more information. 2) Added optional p_ReturnType, p_Delimiter, and r_Count parameters. See the function documentation for more information. 3) Added support for the CF_INACTIVEFONTS flag. If this flag is included, the list of fonts will include hidden fonts. 4) Added support for CF_RASTERONLY, a new custom flag that if included will limit the list of fonts to only raster (binary) fonts.
• Fnt_GetSysColor. Updated to allow a name to be specified (Ex: "COLOR_MENUBAR" or "MenuBar") to determine which system color is to be retrieved.
• Fnt_GetTabbedStringSize. Rewritten to support multiple lines of text. Other changes noted elsewhere.
• Fnt_HardWordBreak. Added optional r_Count output parameter. If specified, this variable contains the total number of lines of text.
• Fnt_RGB2ColorName [Internal function]. Removed the optional p_ReturnDefaultName parameter because it was never used.
• General. The return value of the following functions have been changed from the address to a SIZE or POINT structure (tests as TRUE) or nothing (tests as FALSE) to an object (tests as TRUE) with properties that contain the return values. See the function documentation for more information.
• Fnt_CalculateSize
• Fnt_DialogTemplateUnits2Pixels
• Fnt_GetDefaultGUIMargins
• Fnt_GetDialogBaseUnits
• Fnt_GetMultilineStringSize (deprecTated)
• Fnt_GetMultilineStringSizeDT (deprecated)
• Fnt_GetSize
• Fnt_GetSizeForButton
• Fnt_GetSizeForEdit
• Fnt_GetSizeForText
• Fnt_GetSizeForTextNoPrefix
• Fnt_GetStringSize
• Fnt_GetStringSizeDT
• Fnt_GetTabbedStringSize
• Fnt_Pixels2DialogTemplateUnits
• Fnt_String2DialogTemplateUnits
• Fnt_String2DialogTemplateUnitsDT
• General. The "bold", "italic", "norm", "strike", and "underline" font options are now recognized for any font option that begins with the letters of these options. For example, "strike" and "strikeout" are now treated the same. This matches the behavior of AutoHotkey. This only affects font option in input mode. Font options set/returned by a function are in the same format as before.
• Documentation. The general library documentation has been moved to the _Fnt.Doc.ahk file. Natural Docs v2.0 is used to generate HTML documentation from this file and the function documentation. This HTML document is in a new format that is different from the previous version of this library.
• Documentation, Part 2. A new Fnt_Constants.ahk documentation file has been created. It contains some commonly used Microsoft and custom constants along with the descriptions for those constants. This file is written in an AutoHotkey format but it is for documentation purposes only. It should not be included in any script.
• Examples. Lots of changes. Several new examples. New "Info" examples.
Possible script breakers: OK, there are a lot of possible script breakers. Many developers will not be affected but be sure to review this section carefully.
• Fnt_AddFontFile. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_AutoFormatTabbedText. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included. The Fnt_AutoFormatTabbedText.ahk library file is no longer used and should not be included.
• Fnt_ChooseFnt. When the function returns, it still tests as TRUE if a font is selected and FALSE if the dialog was canceled. However, in this version of the library, a return object (tests as TRUE) is now returned if a font was selected. If the developer was specifically testing for a TRUE (i.e. 1) value (Ex: if Fnt_ChooseFont(...)=True) then the code must be be modified to test that the return value tests as TRUE. Ex: if Fnt_ChooseFont(...). Otherwise, no changes to the code are necessary.
• Fnt_ChooseFntDlg. A few issues... 1) This function has been moved to the new Fnt_UtilGUI.ahk add-on library. If using this function, the Fnt_UtilGUI.ahk and Fnt_Util.ahk add-on libraries must be included. The Fnt_ChooseFontDlg.ahk, Addtooltip.ahk, MoveChildWindow.ahk, and WinGetPosEx.ahk library files are no longer are used and should not be included. 2) In Windows 7+, hidden fonts are now excluded by default. If expecting to see hidden fonts, include the CF_INACTIVEFONTS flag when calling this function.
• Fnt_CloneFont. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_ColorName2RGB. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_CompactPath. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_Color2ColorName [Internal function]. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_Color2RGB [Internal function]. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_CreatePitchAndFamilyFont. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_FontExists. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_FontSizeToFit. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_FontSizeToFitDT. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_FontSizeToFitHeight. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_GetListOfFonts. In Windows 7+, hidden fonts are now excluded by default. If expecting to see hidden fonts, include the CF_INACTIVEFONTS flag when calling this function.
• Fnt_GetMultilineStringSize. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_GetMultilineStringSizeDT. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_HardWordBreak. This function has been moved to the new Fnt_Util.ahk add-on on library. If using this function, the Fnt_Util.ahk add-on library must be included. The Fnt_HardWordBreak.ahk library file is no longer used and should not be included.
• Fnt_GetPos. This function has been moved to the new Fnt_Util.ahk add-on on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_GetTabbedStringSize. This function has been modified to also work on multiple lines of text. If expecting the results to reflect only a single line of text when multiple lines of text have been specified, then the script may need to be modified.
• Fnt_RemoveFontFile. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_RGB2ColorName [Internal function]. This function has been moved to the new Fnt_Util.ahk add-on library. If using this function, the Fnt_Util.ahk add-on library must be included.
• Fnt_TwipsPerPixel. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• Fnt_VertDTUs2Pixels. This deprecated function has been moved to the new Fnt_Deprecated.ahk add-on library. If using this function, the Fnt_Deprecated.ahk add-on library must be included.
• The return value of the following functions have been changed from the address to a SIZE or POINT structure to an object with properties that contain the return values. If the developer was using the return value (rare in most cases), then the script must be modified to accommodate the new return value. No changes are needed if the developer was only using the function's output variables (very common).
• Fnt_CalculateSize
• Fnt_DialogTemplateUnits2Pixels
• Fnt_GetDefaultGUIMargins
• Fnt_GetDialogBaseUnits
• Fnt_GetMultilineStringSize (deprecated)
• Fnt_GetMultilineStringSizeDT (deprecated)
• Fnt_GetSize
• Fnt_GetSizeForButton
• Fnt_GetSizeForEdit
• Fnt_GetSizeForText
• Fnt_GetSizeForTextNoPrefix
• Fnt_GetStringSize
• Fnt_GetStringSizeDT
• Fnt_GetTabbedStringSize
• Fnt_Pixels2DialogTemplateUnits
• Fnt_String2DialogTemplateUnits
• Fnt_String2DialogTemplateUnitsDT
New Functions (main library):
• Fnt_BuildOO. [Internal function] Build an options object.
• Fnt_ChooseFontEx. Extended version of Fnt_ChooseColor. In this version, the character set can be used to select, limit, and subsequently create a font. See the function documentation for more information.
• Fnt_ConvertColor. [Internal function] Convert a color to a 6-digit hexadecimal RGB or BGR value.
• Fnt_CreateFontEx. Extended version of Fnt_CreateFont. In this version, the developer can set the character set of the font to create. This can be useful if Fnt_ChooseFontEx is used to select a font.
• Fnt_CreateFontIndirect. Create a logical font from a LOGFONT structure.
• Fnt_CreateGenericFont. Create a generic font based on pitch and/or font group. This function was created to replace Fnt_CreatePitchAndFamilyFont. It performs similar tasks but it has additional functionality and a workaround to the bugs with the FF_DECORATIVE and FF_SCRIPT flags is included. It should be used instead of Fnt_CreatePitchAndFamilyFont.
• Fnt_GetFontCharSet. Get the character set of a font.
• Fnt_GetInactiveFonts. [Internal function] Load the list of inactive font names (if any) to an associative array.
• Fnt_GetFontTypeFromName. Get the font type from a font name.
• Fnt_IsDeviceFont. Determine if a font is a device font or not.
• Fnt_IsRasterFont. Determine if a font is a raster (binary) font or not.
• Fnt_IsScalableFont. Determine if a font is scalable or not.
• Fnt_IsValidFaceName. Determine if a typeface name is valid or not. See the function documentation for more information.
• Fnt_IsValidFontName. Determine if a font name is valid or not.
• Fnt_Points2Pixels. Convert points to pixels.
• Fnt_Pixels2Points. Convert pixels to points.
New Add-On Functions: Fnt_GetRandomFont.ahk add-on library (new)
• Fnt_GetRandomFont. This function replaces Fnt_RandomFont. It contains several new options.
• Fnt_GetRandomTTFont. This function replaces Fnt_RandomTTFont.
• Fnt_GetRandomTTFPFont. This function replaces Fnt_RandomTTFPFont.
• Fnt_GetRandomTTVPFont. This function replaces Fnt_RandomTTVPFont.
Fnt_Util.ahk add-on library (new)
• Fnt_AddTooltip. Add a tooltip to a GUI control. This function is used by the Fnt_ChooseFontDlg function and some example scripts but it is available for general use.
• Fnt_CalculateFontSizeToFit. Calculate the largest font size that can be used to fit text within a specified area (width and/or height).
• Fnt_DrawText. Draw text to a static control.
• Fnt_DrawTextToBitmap. Draw text to a bitmap.
• Fnt_GetFirstValidFontName. Get the first valid font name from a list of font names.
• Fnt_GetFontInfo. Get information about a logical font.
• Fnt_GetStaticBkColor. Get the background color of a static control or a read-only Edit control.
• Fnt_GetListOfFontSizes. Generate a list of font sizes for a font name. This function is used by the Fnt_ChooseFontDlg function but it is available for general use.
• Fnt_GetWindowRect. Get the position a size of a window. This function is used by the Fnt_ChooseFontDlg function but it is available for general use.
• Fnt_SBSetText. Set the status bar text. This function is used by the Fnt_ChooseFontDlg function but it is available for general use.
• Fnt_SetBitmap. Associate a bitmap with a static control.
Fnt_UtilGUI.ahk add-on library (new)
• Fnt_MoveChildWindow. Move the window relative to the parent window, usually to the center of the parent window. This function was added for use by the Fnt_ChooseFontDlg function but it is available for general use. Deprecated: Deprecated functions are still a part of the library but most have all been moved to the Fnt_Deprecated.ahk add-on library. If any of these functions are needed by current scripts, the Fnt_Deprecated.ahk add-on library must be included. Please note that these functions may be removed in future versions of the project.
• Fnt_ColorName2RGB. Use Fnt_ConvertColor instead. Please note that if an unsupported color name is specified or if the "Default" color name is specified, the value from <Fnt_GetWindowTextColor> is returned. This default is different than the default for the Fnt_ConvertColor function.
• Fnt_CreatePitchAndFamilyFont. Use Fnt_CreateGenericFont instead.
• Fnt_FontExists. Use Fnt_GetFirstValidFontName instead.
• Fnt_FontSizeToFit. Use Fnt_CalculateFontSizeToFit instead.
• Fnt_FontSizeToFitDT. Use Fnt_CalculateFontSizeToFit instead.
• Fnt_FontSizeToFitHeight. Use Fnt_CalculateFontSizeToFit instead.
• Fnt_GetMultilineStringSize. Use Fnt_GetSize or similar function instead.
• Fnt_GetMultilineStringSizeDT. Use Fnt_GetSize or similar function instead.
• Fnt_RandomFont. Use Fnt_GetRandomFont instead.
• Fnt_RandomTTFont. Use Fnt_GetRandomTTFont instead.
• Fnt_RandomTTFPFont. Use Fnt_GetRandomTTFPFont instead.
• Fnt_RandomTTVPFont. Use Fnt_GetRandomTTVPFont instead.
• Fnt_TwipsPerPixel. Rarely (read: never) used function.
• Fnt_VertDTUs2Pixels. Use Fnt_DialogTemplateUnits2Pixels instead.
Housekeeping:
After v4.0 has been installed on your computer, the following add-on library files from previous versions can be deleted. This step is only needed if a previous version of the Fnt library was installed.
v3.0 Possible script breakers:
• Fnt_HardWordBreak. This function has been moved to a separate add-on library file and changes have been made to the function. If this function was called, changes to the script will be necessary. See the function documentation for more information.
• Fnt_GetMultilineStringSize. Removed the optional r_LineCount output parameter. A script error will occur if the parameter was specified. Also, the font's external leading is no longer included when calculating the height. The results may be different than the previous version for some fonts.
• Fnt_GetStringSize. The function has been modified so that the address to a SIZE structure is returned regardless of success or failure. Previously FALSE was returned on failure. Failure is extremely rare (I've never seen it).
• Fnt_TruncateStringToFit. The function has been rewritten to use "GetTextExtentExPoint" instead of "GetTextExtentPoint32" to measure the text. Depending on the font, the results may be different than the previous version. If the string contains control characters like tab, carriage return, or line feed, the results may be significantly different than the previous version.
New Functions:
• Fnt_CalculateSize. Option-rich function to calculate the width and height of text.
• Fnt_CloneFont. Create a logical font with the same attributes of any logical font (thanks jeeswg).
• Fnt_Color2ColorName [Internal function]. Convert a color value (Ex: "FF00FF") into one of 16 color names if a match is found.
• Fnt_Color2RGB [Internal function]. Convert a color value (Ex: "Blue") to it's 6-digit hexadecimal RGB value.
• Fnt_CreatePitchAndFamilyFont. Create a font by pitch and font family rather than by typeface.
• Fnt_CreateTooltipFont. Create a font with the same attributes as the font used in tooltips.
• Fnt_FontSizeToFitDT. The same as Fnt_FontSizeToFit except that "DrawText" is used to measure the text instead of "GetTextExtentPoint32".
• Fnt_GetAverageCharWidth. Calculates the average width of characters in a font. Not to be confused with Fnt_GetFontAvgCharWidth. See the function documentation for more information.
• Fnt_GetDefaultGUIFont. Get the handle to the default GUI font.
• Fnt_GetFontEmHeight. Get the em height of characters in a font.
• Fnt_GetFontQuality. Gets the font's output quality.
• Fnt_GetLongestStringDT. The same as Fnt_GetLongestString except that "DrawText" is used to measure the text instead of "GetTextExtentPoint32".
• Fnt_GetMultilineStringSizeDT. The same as Fnt_GetMultilineStringSize except that "DrawText" is used to measure the text instead of "GetTextExtentPoint32".
• Fnt_GetSize. General purpose function to calculate the width and height of text.
• Fnt_GetSizeForEdit. Calculate the width and height of text that will used in an Edit control.
• Fnt_GetSizeForButton. Calculate the width and height of text that will used in a Button control.
• Fnt_GetSizeForText. Calculate the width and height of text that will used in a Text control.
• Fnt_GetSizeForTextNoPrefix. The same as Fnt_GetSizeForText except that the DT_NOPREFIX format is also used when calculating the size. See the function documentation for more information.
• Fnt_GetStringSizeDT. The same as Fnt_GetStringSize except that "DrawText" is used to measure the text instead of "GetTextExtentPoint32".
• Fnt_GetStringWidthDT. The same as Fnt_GetStringWidth except that "DrawText" is used to measure the text instead of "GetTextExtentPoint32".
• Fnt_GetTabbedStringSize. Calculate the width and height (in pixels) of a string of text. If the string contains one or more tab characters, the tab characters are expanded based upon the specified tab stop size.
• Fnt_GetTooltipFontName. Get the typeface name of the font used in tooltips.
• Fnt_GetTooltipFontSize. Get the point size of the font that is used in tooltips.
• Fnt_IsFont. Determines if the hFont parameter contains the handle to valid logical font.
• Fnt_RGB2ColorName [Internal function]. Convert a RGB value into one of 16 color names if a match is found.
• Fnt_String2DialogTemplateUnitsDT. The same as Fnt_String2DialogTemplateUnits except that "DrawText" is used to measure the text instead of "GetTextExtentPoint32".
• Fnt_TruncateStringWithEllipsis. Similar to Fnt_TruncateStringToFit except that if the string is truncated, the end of the string is replaced with an ellipses.
New Helper/Debug Functions:
• New functions that set/update some of the options within a font options string (Ex: "s9 bold cBlue"). New functions include Fnt_FOGetQuality, Fnt_FORemoveQuality, Fnt_FOSetQuality, Fnt_FOGetWeight, Fnt_FORemoveWeight, and Fnt_FOSetWeight. See the function documentation for more information.
• New functions to get the font options of the non-client fonts. New functions include Fnt_GetCaptionFontOptions, Fnt_GetMenuFontOptions, Fnt_GetMessageFontOptions, Fnt_GetSmCaptionFontOptions, Fnt_GetStatusFontOptions, and Fnt_GetTooltipFontOptions.
• Fnt_GetBoldGUIFont. Similar to Fnt_GetDefaultGUIFont except that a font with font weight of 700 (i.e. Bold) is returned.
• Fnt_GetLastTooltip. Get the handle to last created tooltip control (if any).
• Fnt_GetLogicalFontName. Get the typeface name specified when the font was created.
• Fnt_GetLogicalFontOptions. Get the font options specified (explicitly or by default) when the font was created.
• Fnt_SetTooltipFont. Creates a font and sets the last created tooltip control to use the font. (The idea to combine this functionality into a single function by rommmcek. Thanks.)
New Add-On Functions:
• Fnt_AutoFormatTabbedText. Auto-format tab-delimited text so the columns will align correctly when displayed.
• Fnt_ChooseFontDlg. [Preview/Experimental] Alternative to the Fnt_ChooseFont function. See the function documentation for more information.
• Fnt_RandomFont. Get a random font (no filter).
Bug Fixes, Updates, and Enhancements:
• Fnt_ChooseFont. [1] Enhancements to automatically add font options that will allow the dialog to preselect default and/or necessary options for the specified font in some cases. [2] Added support for the "h" (height) option. See the function documentation for more information.
• Fnt_CreateFont. [1] If all function parameters are null or unspecified, the handle to the default GUI font (a stock object) is returned. Previously a font with the same/similar attributes of the default GUI font was created in this case. [2] Added 3 new options (r_Options parameter): 1) "h" (height) option to allow the developer to specify the height of the font and 2 & 3) "norm" and "-s" options so that the function is more compatible with the AutoHotkey "gui Font" command. See the function documentation for more information. [3] The intent of the "bold" option (r_Options parameter) has been changed from setting the weight to exactly 700 to setting the weight to the heaviest weight available for the font. The heaviest weight is 700 for most fonts but it can be higher for a few fonts. [4] Minor changes to the function so that it better emulates the behavior of AutoHotkey. Most of the changes relate to what occurs when a "s" (size) option is not specified.
• Fnt_EnumFontFamExProc. Added support for a font family filter.
• Fnt_FontExists. Minor performance improvements.
• Fnt_GetDefaultGUIMargins. Valid values for the p_DPIScale parameter changed from TRUE (the default), FALSE, and "A" (for automatic) to just TRUE (the default) and FALSE. The option of "A" (for automatic) was removed because as of v2.0, the library is designed to only run on AutoHotkey v1.1+. Since "A" also tests as TRUE (the default), this modification is not a potential script breaker since all scripts will continue to return the same value if p_DPIScale is set to "A".
• Fnt_GetFontOptions. Font quality is now one of the possible font options returned by this function (Ex: "q3"). It is returned if the font quality value is not 2 (the AutoHotkey default).
• Fnt_GetListOfFonts. Added documentation for the new font family filter.
• Fnt_GetMultilineStringSize. Removed the optional r_LineCount output parameter. The value assigned to this variable did not always reflect the calculated number of lines. Also, the font's external leading is no longer included when calculating the height. The result is more accurate for any font with a non-zero external leading.
• Fnt_HardWordBreak add-on. The function has been updated to support additional values in some of the parameters. Also, the return value has changed. See the function documentation for more information.
• Fnt_TruncateStringToFit. The function has been rewritten to use "GetTextExtentExPoint" instead of "GetTextExtentPoint32" to measure the text. The results more consistently match the results of the new Fnt_TruncateStringWithEllipsis function.
• Documentation. Added a "Terminology" group and there are significant updates to the "Issues and Considerations" group.
• Examples. Many new and enhanced examples.
Helper or Preview/Experimental Functions - Bug Fixes, Updates, and Enhancements:
• Fnt_FOGetSize. Added optional p_IgnoreZero parameter. See the function documentation for more information.
• Fnt_FOIncrementSize. Minor changes to support the enhancements to Fnt_FOGetSize.
• Fnt_FOSetSize. Updated support for a "s" (size) option with a value of 0.
• Fnt_FontSizeToFitHeight. Updates to increase the efficiency of the function.
v2.0 Requirements:
This and future versions of this library are designed to run on all versions of AutoHotkey v1.1+: ANSI, Unicode, and Unicode 64-bit.
Possible script breakers:
• Fnt_IsVectorFont removed. The function has no practical value at this time.
New Functions:
• Fnt_AddFontFile. Add font(s) from a font file. Ex: "MySpecialFont.ttf"
• Fnt_CompactPath. Shortens a file path to fit within a given pixel width.
• Fnt_FontExists. [Preview/Experimental] Determines if a font exists. Can also be used to find the first available font in a list of fonts.
• Fnt_GetTotalRowHeight. Calculate the height of a given number of rows of text for a font.
• Fnt_GetLongestString. Determines the longest string (measured in pixels) from a list of strings.
• Fnt_HardWordBreak. [Preview/Experimental] Inserts hard line breaks into a string of text so that the maximum width of each line is less than or equal to a specified width, in pixels.
• Fnt_RemoveFontFile. Remove the font(s) added by Fnt_AddFontFile.
Bug fixes, Changes, and Enhancements:
• Fnt_EnumFontFamExProc [Internal function]. Receives the p_Flags parameter from Fnt_GetListOfFonts (or any function that triggers it) to limit the number of fonts returned. Added new custom flags to increase the options available.
• Fnt_GetListOfFonts. Added an optional p_Flags parameter that can filter the fonts that are returned.
• Fnt_GetMultilineStringSize. Added the r_LineCount output parameter (optional).
• Fnt_SetFont. Fixed to use the default GUI font if a font was not specified.
• Fnt_Convert2Hex [Internal function] removed. Not needed with AutoHotkey v1.1+.
• Examples. Added several new examples and and enhanced some of the examples.
New Add-On Functions: Add-On functions are functions stored in separate library files. Ex: Fnt_SpecialFunction.ahk. They must be included separately in order to be used and they require the Fnt library in order to run. In some cases, add-on functions may require other libraries in order to run.
• Fnt_RandomTTFont. Get a random True Type font.
• Fnt_RandomTTFPFont. Get a random fixed pitch True Type font.
• Fnt_RandomTTVPFont. Get a random variable pitch True Type font.
v1.0 New Functions:
• Fnt_GetDialogBackgroundColor [Internal function]. Get the current dialog background color.
• Fnt_ColorName2RGB [Internal function]. Convert color names to 6-digit hexadecimal RGB values.
• Fnt_FontSizeToFitHeight. [Preview/Experimental] Determines the largest font size that can be used to fit within a specified height.
• Fnt_GetSysColor [Internal function]. Get a system color. Return value is an AutoHotkey hexadecimal value that always has 6 hexadecimal digits. Ex: 0x0034F6.
• Fnt_GetWindowColor [Internal function]. Get the current window background color.
• Fnt_GetWindowTextColor [Internal function]. Get the current window text color.
Bug fixes:
• Fnt_ChooseFont. For the p_Effects=True option, if no color option is specified on input, bug fixed so that the actual default text color is pre-selected instead of assuming Black. On output, "Default" is set as the color on the color option (Ex: "cDefault") if the default text color is selected. This change keeps subsequent "gui Font" commands from setting a custom color or if a custom color was previously set, to reset the text color to the system default text color.
Updates:
• Fnt_FontSizeToFit. Removed the p_Height parameter (never used).
• New and updated examples.
v0.9 (Preview) New Functions:
• New helper functions that set/update some of the options within a font options string (Ex: "s9 bold cBlue"). New functions include Fnt_FODecrementSize, Fnt_FOGetColor, Fnt_FOGetSize, Fnt_FOIncrementSize, Fnt_FORemoveColor, Fnt_FOSetColor, and Fnt_FOSetSize. Additional font options helper functions may be added in the future.
• Fnt_HorzDTUs2Pixels. Converts horizontal dialog template units to pixels.
• Fnt_VertDTUs2Pixels. Converts vertical dialog template units to pixels.
• Fnt_UpdateTooltip. Forces a tooltip control to be redrawn. Used in conjunction with Fnt_SetFont when setting the font of a tooltip control.
Updates:
• Fnt_CreateFont. Quality option (Ex: "q3") added to list of available font options.
• New example and minor updates to a few examples.
v0.8 (Preview) New Functions:
• Fnt_GetCaptionFontName. Get the typeface name of the caption font.
• Fnt_GetCaptionFontSize. Get the point size of the caption font.
• Fnt_GetMenuFontName. Get the typeface name of the font used in menu bars.
• Fnt_GetMenuFontSize. Get the point size of the font that is used in menu bars.
• Fnt_GetMessageFontName. Get the typeface name of the font that is used in message boxes.
• Fnt_GetMessageFontSize. Get the point size of the font that is used in message boxes.
• Fnt_GetSmCaptionFontName. Get the typeface name of the small caption font.
• Fnt_GetSmCaptionFontSize. Get the point size of the small caption font.
• Fnt_GetStatusFontName. Get the typeface name of the font used in status bars and tooltips.
• Fnt_GetStatusFontSize. Get the point size of the font that is used in status bars and tooltips.
v0.7 (Preview) Bug Fixes:
• Fnt_GetDefaultGUIMargins. For AutoHotkey v1.1.11+, the function was not calculating the default margins correctly when using a non-standard DPI.
New Functions:
• Fnt_GetPos. Get the actual position and size of a GUI control.
• Fnt_TruncateStringToFit. Returns a string that is less than or equal to a specified width, in pixels. Thanks to arcticir for the idea and for testing the function.
Updates/Enhancements:
• Fnt_DialogTemplateUnits2Pixels, Fnt_Pixels2DialogTemplateUnits, and Fnt_String2DialogTemplateUnits. Performance significantly improved when called multiple times with the same font.
• Fnt_GetDefaultGUIMargins. Added optional p_DPIScale parameter. See the function documentation for the details.
• Fnt_GetMultilineStringSize. Updated for improved performance.
• Fnt_GetFont and Fnt_SetFont reset back to pre-v0.5 state. The additional code added in v0.5 was unnecessary.
• New and updated examples.
v0.6 (Preview) Potential Script Breakers:
• Fnt_GetMaxStringSize renamed to Fnt_GetMultilineStringSize. All parameters remain the same.
• Fnt_GetDefaultGUIMargins. Return value changed to an address of a POINT structure. Output variables remain the same.
Bug Fixes:
• Fnt_ChooseFont fixed to correctly return font weights other than Normal (400) or Bold (700).
New Functions:
• Fnt_CreateCaptionFont. Creates a font with the same attributes as the caption font.
• Fnt_CreateMenuFont. Creates a font with the same attributes as the font used in menu bars.
• Fnt_CreateMessageFont. Creates a font with the same attributes as the font used in message boxes.
• Fnt_CreateSmCaptionFont. Creates a font with the same attributes as the small caption font.
• Fnt_CreateStatusFont. Creates a font with the same attributes as the font used in status bars and tooltips.
• Fnt_DialogTemplateUnits2Pixels. Converts dialog template units to pixels.
• Fnt_FontSizeToFit. [Preview/Experimental] Determines the largest font size that can be used to fit a string within a specified space.
• Fnt_GetDialogBaseUnits. Collects the dialog base units for a font.
• Fnt_GetNonClientMetrics. Get the metrics associated with the non-client area of non-minimized windows.
• Fnt_Pixels2DialogTemplateUnits. Convert pixels to dialog template units.
• Fnt_String2DialogTemplateUnits. Converts a string to dialog template units.
Updates/Enhancements:
• Fnt_ChooseFont. Common color names (Ex: Red, Green, Blue, etc.) are now supported for the color option of the p_Options parameter. Note: Color names are only supported on input. A 6-digit hex RGB color value (Ex: 0000FF) is always set on output.
• Several new examples.
v0.5 (Preview) Fixes/Updates/Enhancements:
• Fnt_ChooseFont updated to no longer use the AutoHotkey "SetFormat, Integer" command which could potentially slow down some scripts.
• Fnt_GetFont and Fnt_SetFont updated to work on both visible and hidden windows.
• Minor documentation updates.
v0.4 (Preview) New Functions:
• Fnt_GetMaxStringSize. Calculate the size of a multiline string. Thanks to Verdlin for the idea.
Fixes/Updates/Enhancements:
• Fixed Fnt_ChooseFont to work on x64. Thanks to maestrith for identifying many of the correct offsets for x64 and to okram for identifying the outstanding offsets and for testing all of the changes.
• Minor changes to a few functions to correctly support x64.
• Added example to set the width of a tooltip.
• Added example to calculate the complete size (w+h) of various controls.
v0.3 (Preview) New Functions:
• Fnt_GetStringWidth. Shell call to Fnt_GetStringSize to get the width of the specified string.
Updates/Enhancements:
• Minor changes to a few functions.
• New example to set the font of a tooltip. Thanks to uname for the idea.
v0.2 (Preview) New Functions:
• Fnt_EnumFontFamExProc [Internal function]. The default EnumFontFamiliesEx callback function for the Fnt library. Currently used by Fnt_GetListOfFonts.
• Fnt_GetListOfFonts. Generate a list of font names.
• Fnt_IsFixedPitchFont. Returns TRUE if the font is a fixed pitch font.
• Fnt_IsTrueTypeFont. Returns TRUE if the font is a TrueType font.
• Fnt_IsVectorFont. Returns TRUE if the font is a vector font.
Updates/Enhancements:
• Fnt_ChooseFont. Changes: 1) SizeMin and SizeMax options added to the p_Options parameter. These options allow the developer to limit the range of font sizes that can be entered/selected. 2) Added p_Flags parameter. [Optional] Additional ChooseFont flags can be added via this parameter. Note: The p_Flags parameter is an advanced feature.
• Fnt_GetFontOptions. Changes: 1) Added a "w{font weight}" return option to indicate the weight of the font. This option is only returned if the font weight is not normal (400) and not bold (700). 2) The "bold" return option is now only returned if the font weight is exactly 700.
• New and updated examples.
v0.1 (Preview)
First release.
Last edited by jballi on 28 Jun 2023, 03:54, edited 11 times in total.
Introduction
The latest release of the Fnt library introduces functions that convert to and from Dialog Template Units. This topic can be confusing and sometimes frustrating and so I created this document in an attempt to generate a better understanding of the subject.
Stuff To Know
This document discusses "dialog base units" and "dialog template units". Be careful. These terms look very similar but they describe different types of measurement. To help differentiate the terms, I've given them different colors so that dialog base units won't be easily confused with dialog template units. This document may look a bit like a coloring book but I hope that it helps.
These terms are often prepended with "horizontal" or "vertical". For example: horizontal dialog template units. "Horizontal" refers to the width or x-Axis of the measurement. "Vertical" refers to the height or y-Axis of the measurement.
Background and Executive Summary
Someone a long time ago figured out that the font used in a window can be used to determine the size of the window and/or the size of objects in the window. The original idea was a means of controlling the size of system dialogs. If the system font was small, then the dialog window was created to be one size. If the system font was large, then the same dialog was created to be a larger size to accommodate for the larger font.
Dialog Template Units are font-based units of measurement. They are used to specify the size (width and/or height) of a window or GUI control without knowing the font or font size that will be used to populate the text within the window and/or GUI control. The unfortunate name is a result of defining a unit of measurement within dialog box templates which are structures used by the DialogBox and CreateDialog functions.
Dialog Base Units Everything is "based" on Dialog Base Units.
A horizontaldialog base unit is the average width, in pixels, of all of the uppercase and lowercase Roman characters of a font, i.e. the average width of this string: "AaBbCc...Zz". A verticaldialog base unit is equal to the height, in pixels, of the font.
Dialog Template Units Dialog Template Units are just smaller units of Dialog Base Units.
There are 4horizontaldialog template units for each horizontal dialog base units. There are 8verticaldialog template units for each vertical dialog base units.
Improving Understanding
There are a few facts and mnemonics that should make it a bit easier to understand how to convert to or from dialog template units.
Horizontal Horizontaldialog template units are based on horizontaldialog base units which are based on the width of a average character of a font. So, instead of horizontal dialog template units, think of the number of "average characters" of a font.
There are 4 horizontal dialog template units for every "average character" of a font. So, to convert "average characters" to dialog template units, multiply the number of "average characters" by 4. For example, to create a GUI control that is 60 "average characters" in width, specify 240 (60 times 4) horizontal dialog template units.
To convert horizontal dialog template units back into "average characters", divide by 4. For example, 500 horizontal dialog template units is equal to 125 (500 divided by 4) "average characters".
Vertical
Don't worry too much about verticaldialog template units. They are equal to factor (8:1) of the height of the font. When measuring a single line of text, the value will always be 8. For two lines of text, the value will always be 16. And so on. This measurement is not as valuable because 1) the height of the font is always available and 2) calculating the height of a control is a little more complicated than knowing the height of the font.
When converting fromverticaldialog template units, just divide by 8. For example, 80 verticaldialog template units is equal to 10 verticaldialog base units which is equal to the height of 10 characters of a font.
Uses Dialog template units are rarely used outside of the dialog template structure but the methodology used to convert to/from them does provide value. In general, the library functions can be used to calculate the size of a GUI control before it is created or after the font is changed on the control. Also, the functions can be used to set the tab stops on an Edit or Rich Edit control which are set in dialog template units. I originally created these functions to support this feature.
The Fnt library includes a few examples that use the dialog template units functions. They include:
Example - Dialog Template Units.ahk
Example - Set Tab Stops on Edit Control.ahk
I've modified several other library examples to use the dialog template units functions to help format the data that is displayed as a part of the output of the example.
f:=StrSplit(".;8a-@sdf1|sdfSdf无可奈何花落去士大夫9ESDFKOOI")
Loop 10
{
b:=""
Loop
{
Random, d, 1, f.MaxIndex()
b.=f[d]
a:=Fnt_GetStringSize(1,b)
if (a>=400)
{
b:=a " " b
Break
}
}
Menu, Test, Add, % b "...", Test
}
Menu, Test, Show
Test:
Return
Fnt_GetStringSize(hFont,p_String)
{
Static Dummy6596
,DEFAULT_GUI_FONT:=17
,HWND_DESKTOP :=0
,SIZE
PtrType:=(A_PtrSize=8) ? "Ptr":"UInt"
;-- If needed, get the handle to the default GUI font
if not hFont
hFont:=DllCall("GetStockObject","Int",DEFAULT_GUI_FONT)
;-- Select the font into the device context for the desktop
hDC :=DllCall("GetDC",PtrType,HWND_DESKTOP)
hFont_Old:=DllCall("SelectObject",PtrType,hDC,PtrType,hFont)
;-- Get string size
VarSetCapacity(SIZE,8,0)
RC:=DllCall("GetTextExtentPoint32"
,PtrType,hDC ;-- hDC
,"Str",p_String ;-- lpString
,"Int",StrLen(p_String) ;-- c (string length)
,PtrType,&SIZE) ;-- lpSize
;-- Housekeeping
DllCall("SelectObject",PtrType,hDC,PtrType,hFont_Old)
;-- Necessary to avoid memory leak
DllCall("ReleaseDC",PtrType,HWND_DESKTOP,PtrType,hDC)
;-- Return to sender
if RC
Return NumGet(SIZE,0,"Int")
}
arcticir wrote:I ask, why do I use Fnt_GetStringWidth () Gets the width is not uniform it?
such as unified menu width:
Hey arcticir,
With a double-byte character set, you are definitely getting into an area that is out of my league but I'm hoping that it's just an apples vs. oranges problem. You are testing the width of a string using the default GUI font but using the system Menu font to display the string. Try this.
I'm sorry, I'm going to need a little more help with this one. When you say, "calculate the width of each word", what does a "word" represent? In your example, 1) what does the "40" represent and 2) what is returned?, i.e. what is stored in the "a" variable? It would be very helpful if you could give me a more detailed example and/or more information on what you you are trying to accomplish. Thanks.
If I read this requirement correctly, it reads something like, "Give me the portion of a string that is less than or equal to a specified number of pixels of a specified font."
I do see something like a Fnt_TruncateStringToFit function in the future (thanks for the idea) but I don't have anything for now. It's not very efficient, but a brute-force method (checking one character at a time) like your example is the fastest thing to program and will probably return the value in a very reasonable amount of time. I'm sorry I couldn't be more helpful.
arcticir, I've written a general purpose function to do the job. I've named it Fnt_TruncateStringToFit for now. It was designed to try to make the smallest number of calls to external functions, specifically Fnt_GetStringSize, as possible. After the methodology has been vetted (and if merited), I will update it for additional efficiency.
Since you have a real-life use for this function, I will PM you a copy of the function for your review. Please give it try at your convenience. Be aware that the version I'm posting is in full debug mode. If you have a debug viewer, you can see what's going on in the background. If you have any additional questions, problems, or comments on this topic, please PM me.
v0.9 (Preview)
New font options "helper" functions and a few new miscellaneous functions. See the Release Notes section of the first post for the details.
v1.0
A bug fix, a new function, and a few new/updated examples. See the Release Notes section of the first post for the details.
Please note that this version will be last version of the library to support all versions of AutoHotkey. Future versions (if any) will only support AutoHotkey v1.1+.
I've noticed this several times over the years but because the status bar is an easily-forgotten component of a window, I did not put two and two together until recently.
AutoHotkey sets the font for the text displayed in the status bar. If the developer does not specify a font or the gui Font command is used without parameters before the status bar is added, the default GUI font is used. Otherwise, the last font set before the status bar is added is used.
The thing is, the font used to draw the text in the status bar is supposed to be a component of Non-client Metrics. These are system-wide parameters used by all windows. "Non-client" refers to all components of the window that are not part of the client. They include the border, caption, menu, status bar, etc. From a font perspective, this includes the caption font, menu font, status font (status bar and tooltips) and message font (MsgBox dialog).
Non-client attributes like the status bar font are set by default when the user selects a theme and text size (DPI). If desired, the user can customize one or more of these items by going to the Control Panel (Window Color and Appearance dialog) and change the font, size, color, etc. Non-client attributes can also be set programmatically (one example here) although I haven't been able to come up with an real-life reason to do so.
So, what's wrong with using the default GUI font for the status bar? Absolutely nothing. It's a very readable font and because the font size is smaller on many themes, you can fit a lot of text in small amount of space. The problem is that it's not the font selected by the user when they selected the theme, DPI, or when they customized it in the Control Panel. For many themes, the non-client font used for the status bar is a bit larger and easier to read than the default GUI font.
Instructing AutoHotkey to use the system non-client font for the status bar is easy with the Fnt library. The best time to do it is when the status bar is added to the GUI. For example:
hSBFont:=Fnt_CreateStatusFont()
Fnt_SetFont(hSB,hSBFont,True)
;-- This assumes that hSB is the handle to the status bar
I recently started making these changes to some of my scripts that have a GUI with a status bar. For my theme and DPI, the font size is a bit larger and easier to read than the default GUI font. In addition, it matches the menu font.
v2.0
Minor bug fix, several enhancements, several new functions, and new and updated examples. See the Release Notes section of the first post for the details.
This and future versions of the library will only run on AutoHotkey v1.1+.