Jump to content

StringSize - M23 - BugFix version 27 Dec 23


Melba23
 Share

Recommended Posts

There is an error with changing font size:

#include <StringSize.au3>

$String='Long string, very very long'
$a=_StringSize($String, 18)

#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ### Form=

$Form1 = GUICreate("Form1", $a[2], $a[3])
GUISetFont(18)
$Label1 = GUICtrlCreateLabel($a[0], 0, 0, $a[2], $a[3])
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit

    EndSwitch
WEnd

Solve:

GuiSetFont doesn't accept keyword Default for Fontname, there needs empty string "".

Corrected UDF code:

#include-once

; #INDEX# ============================================================================================================
; Title .........: _StringSize
; AutoIt Version : v3.2.12.1 or higher
; Language ......: English
; Description ...: Returns size of rectangle required to display string - width can be chosen
; Remarks .......:
; Note ..........:
; Author(s) .....: Melba23
; ====================================================================================================================

;#AutoIt3Wrapper_au3check_parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6

; #CURRENT# ==========================================================================================================
; _StringSize: Returns size of rectangle required to display string - maximum permitted width can be chosen
; ====================================================================================================================

; #INTERNAL_USE_ONLY#=================================================================================================
; _StringSize_Error: Returns from error condition after DC and GUI clear up
; ====================================================================================================================

; #FUNCTION# =========================================================================================================
; Name...........: _StringSize
; Description ...: Returns size of rectangle required to display string - maximum permitted width can be chosen
; Syntax ........: _StringSize($sText[, $iSize[, $iWeight[, $iAttrib[, $sName[, $iWidth]]]]])
; Parameters ....: $sText   - String to display
;                  $iSize   - [optional] Font size in points - default AutoIt GUI default
;                  $iWeight - [optional] Font weight (400 = normal) - default AutoIt GUI default
;                  $iAttrib - [optional] Font attribute (0-Normal, 2-Italic, 4-Underline, 8 Strike - default AutoIt
;                  $sName   - [optional] Font name - default AutoIt GUI default
;                  $iWidth  - [optional] Width of rectangle - default is unwrapped width of string
; Requirement(s) : v3.2.12.1 or higher
; Return values .: Success - Returns array with details of rectangle required for text:
;                  |$array[0] = String formatted with @CRLF at required wrap points
;                  |$array[1] = Height of single line in selected font
;                  |$array[2] = Width of rectangle required to hold formatted string
;                  |$array[3] = Height of rectangle required to hold formatted string
;                  Failure - Returns 0 and sets @error:
;                  |1 - Incorrect parameter type (@extended = parameter index)
;                  |2 - Failure to create GUI to test label size
;                  |3 - DLL call error - extended set to indicate which
;                  |4 - Font too large for chosen width - longest word will not fit
; Author ........: Melba23
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: Yes
;=====================================================================================================================
Func _StringSize($sText, $iSize = Default, $iWeight = Default, $iAttrib = Default, $sName = Default, $iWidth = 0)

    Local $avSize_Info[4], $aRet, $iLine_Width = 0, $iLast_Word, $iWrap_Count
    Local $hLabel_Handle, $hFont, $hDC, $oFont, $tSize = DllStructCreate("int X;int Y")

    ; Correction $sName:
    If Number($sName) = -1 Then $sName=""; If -1 or Default used, set to empty string.

    ; Check parameters are correct type
    If Not IsString($sText) Then Return SetError(1, 1, 0)
    If Not IsNumber($iSize) And $iSize <> Default   Then Return SetError(1, 2, 0)
    If Not IsInt($iWeight)  And $iWeight <> Default Then Return SetError(1, 3, 0)
    If Not IsInt($iAttrib)  And $iAttrib <> Default Then Return SetError(1, 4, 0)
    If Not IsString($sName) And $sName <> Default   Then Return SetError(1, 5, 0)
    If Not IsNumber($iWidth) Then Return SetError(1, 6, 0)

    ; Create GUI to contain test labels, set to required font parameters
    Local $hGUI = GUICreate("", 1200, 500, 10, 10)
        If $hGUI = 0 Then Return SetError(2, 0, 0)
        GUISetFont($iSize, $iWeight, $iAttrib, $sName)

    ; Store unwrapped text
    $avSize_Info[0] = $sText

    ; Ensure EoL is @CRLF and break text into lines
    If StringInStr($sText, @CRLF) = 0 Then StringRegExpReplace($sText, "[\x0a|\x0d]", @CRLF)
    Local $asLines = StringSplit($sText, @CRLF, 1)

    ; Draw label with unwrapped lines to check on max width
    Local $hText_Label = GUICtrlCreateLabel($sText, 10, 10)
    Local $aiPos = ControlGetPos($hGUI, "", $hText_Label)

    GUISetState(@SW_HIDE)

    GUICtrlDelete($hText_Label)

    ; Store line height for this font size after removing label padding (always 8)
    $avSize_Info[1] = ($aiPos[3] - 8)/ $asLines[0]
    ; Store width and height of this label
    $avSize_Info[2] = $aiPos[2]
    $avSize_Info[3] = $aiPos[3] - 4 ; Reduce margin

    ; Check if wrapping is required
    If $aiPos[2] > $iWidth And $iWidth > 0 Then

        ; Set returned text element to null
        $avSize_Info[0] = ""

        ; Set width element to max allowed
        $avSize_Info[2] = $iWidth

        ; Set line count to zero
        Local $iLine_Count = 0

        ; Take each line in turn
        For $j = 1 To $asLines[0]

            ; Size this line unwrapped
            $hText_Label = GUICtrlCreateLabel($asLines[$j], 10, 10)
            $aiPos = ControlGetPos($hGUI, "", $hText_Label)
            GUICtrlDelete($hText_Label)

            ; Check wrap status
            If $aiPos[2] < $iWidth Then
                ; No wrap needed so count line and store
                $iLine_Count += 1
                $avSize_Info[0] &= $asLines[$j] & @CRLF
            Else
                ; Wrap needed so need to count wrapped lines

                ; Create label to hold line as it grows
                $hText_Label = GUICtrlCreateLabel("", 0, 0)
                ; Initialise Point32 method
                $hLabel_Handle = ControlGetHandle($hGui, "", $hText_Label)
                ; Get DC with selected font
                $aRet = DllCall("User32.dll", "hwnd", "GetDC", "hwnd", $hLabel_Handle)
                If @error Then _StringSize_Error(3, 1, $hLabel_Handle, 0, $hGUI)
                $hDC = $aRet[0]
                $aRet = DllCall("user32.dll", "lparam", "SendMessage", "hwnd", $hLabel_Handle, "int", 0x0031, "wparam", 0, "lparam", 0) ; $WM_GetFont
                If @error Then _StringSize_Error(3, 2, $hLabel_Handle, $hDC, $hGUI)
                $hFont = $aRet[0]
                $aRet = DllCall("GDI32.dll", "hwnd", "SelectObject", "hwnd", $hDC, "hwnd", $hFont)
                If @error Then _StringSize_Error(3, 3, $hLabel_Handle, $hDC, $hGUI)
                $oFont = $aRet[0]
                If $oFont = 0 Then _StringSize_Error(3, 4, $hLabel_Handle, $hDC, $hGUI)

                ; Zero counter
                $iWrap_Count = 0

                While 1

                    ; Set line width to 0
                    $iLine_Width = 0
                    ; Initialise pointer for end of word
                    $iLast_Word = 0

                    For $i = 1 To StringLen($asLines[$j])

                        ; Is this just past a word ending?
                        If StringMid($asLines[$j], $i, 1) = " " Then $iLast_Word = $i - 1
                        ; Increase line by one character
                        Local $sTest_Line = StringMid($asLines[$j], 1, $i)
                        ; Place line in label
                        GUICtrlSetData($hText_Label, $sTest_Line)

                        ; Get line length into size structure
                        $iSize = StringLen($sTest_Line)
                        DllCall("GDI32.dll", "int", "GetTextExtentPoint32", "hwnd", $hDC, "str", $sTest_Line, "int", $iSize, "ptr", DllStructGetPtr($tSize))
                        If @error Then _StringSize_Error(3, 5, $hLabel_Handle, $hDC, $hGUI)
                        $iLine_Width = DllStructGetData($tSize, "X")

                        ; If too long exit the loop
                        If $iLine_Width >= $iWidth - Int($iSize / 2) Then ExitLoop
                    Next

                    ; End of the line of text?
                    If $i > StringLen($asLines[$j]) Then
                        ; Yes, so add final line to count
                        $iWrap_Count += 1
                        ; Store line
                        $avSize_Info[0] &= $sTest_Line & @CRLF
                        ExitLoop
                    Else
                        ; No, but add line just completed to count
                        $iWrap_Count += 1
                        ; Check at least 1 word completed or return error
                        If $iLast_Word = 0 Then
                            _StringSize_Error(4, 0, $hLabel_Handle, $hDC, $hGUI)
                        EndIf
                        ; Store line up to end of last word
                        $avSize_Info[0] &= StringLeft($sTest_Line, $iLast_Word) & @CRLF
                        ; Strip string to point reached
                        $asLines[$j] = StringTrimLeft($asLines[$j], $iLast_Word)
                        ; Trim leading whitespace
                        $asLines[$j] = StringStripWS($asLines[$j], 1)
                        ; Repeat with remaining characters in line
                    EndIf

                WEnd

                ; Add the number of wrapped lines to the count
                $iLine_Count += $iWrap_Count

                ; Clean up
                DllCall("User32.dll", "int", "ReleaseDC", "hwnd", $hLabel_Handle, "hwnd", $hDC)
                If @error Then _StringSize_Error(3, 6, $hLabel_Handle, $hDC, $hGUI)
                GUICtrlDelete($hText_Label)

            EndIf

        Next

        ; Convert lines to pixels and add reduced margin
        $avSize_Info[3] = ($iLine_Count * $avSize_Info[1]) + 4

    EndIf

    ; Clean up
    GUIDelete($hGUI)

    ; Return array
    Return $avSize_Info

EndFunc ; => _StringSize

; #INTERNAL_USE_ONLY#============================================================================================================
; Name...........: _StringSize_Error
; Description ...: Returns from error condition after DC and GUI clear up
; Syntax ........: _StringSize_Error($iError, $iExtended, $hLabel_Handle, $hDC, $hGUI)
; Parameters ....: $iError  - required error value to return
;                  $iExtended - required extended value to return
;                  $hLabel_Handle, $hDC, $hGUI - variables as set in _StringSize function
; Author ........: Melba23
; Modified.......:
; Remarks .......: This function is used internally by _StringSize
; ===============================================================================================================================
Func _StringSize_Error($iError, $iExtended, $hLabel_Handle, $hDC, $hGUI)

    ; Release DC if created
    DllCall("User32.dll", "int", "ReleaseDC", "hwnd", $hLabel_Handle, "hwnd", $hDC)
    ; Delete GUI
    GUIDelete($hGUI)
    ; Return with extended set
    Return SetError($iError, $iExtended, 0)

EndFunc ; => _StringSize_Error
Link to comment
Share on other sites

  • Moderators

xrewndel,

Thank you for that. ;)

I have amended the code in the first post to correct the error - although I have not done it quite as you suggested. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • 3 months later...
  • Moderators

kickarse.

Glad you like it. :x

Is there any way to add an option for max height?

Not as such, but as the UDF calculates the height of a line and the overall string when wrapped, I can see several ways to code a wrapper which deals with heights (see llewxam's posts above for an example).

Could you be a bit more specific about what you want to do? I can then see how we might go about it. :P

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

Mat,

The UDF returns the height of the rectangle needed to hold the string for a given width, so I fully intend to leave it to the coder to decide whether that value is too great and that they should look at other ways of displaying the mass of text. For example, use a large scrolling label within in a child GUI - or just dump the text in an edit control and let Windows sort out the scrollbars. :shifty:

I have a number of ideas as to why the OP might want to limit the height, but I am unwilling to expend any of my little grey cells developing solutions until I know exactly what he wants. If it is to have the rectangle with a height as close as possible to a defined value, then the problem is trivial - if the height value must be more exact, then life gets a little more complicated as we are probably looking at adjusting font sizes to fit. :P

Anyway, when the OP lets me know his desiderata, I am sure something can be done to satisfy them. :x

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • 4 months later...

I seem to be having trouble with this.

I am using it in my Weather program and currently its not fitting.

Here is the script I am running, I have OverViewStatus[1] set to not change at the moment for testing, and its not fitting in the GUI. You will need the WeatherUDF, which is provided at the bottom. Thanks in advance :unsure:

(The StringSizing starts at line 42 and ends at 44)

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GDIPlus.au3>
#Include <WinAPI.au3>
#include "WeatherUDF.au3"
#include "StringSize.au3"
#include <array.au3>

Opt("GUIOnEventMode", 1)

Global $ZipCode, $GUI, $hgraphic, $himage, $Time1GUI, $Time2Gui, $Time3Gui, $Time4Gui

$ZipCode = InputBox("Zip code", "Please input your zip code")

Global $h_Desktop_SysListView32
_GetDesktopHandle()

$Width = @DesktopWidth
$Height = @DesktopHeight
    _GetOverViewTime()
    _GetOverViewTemperature()
    _GetOverViewImages()
    _GetOverViewStatus()
    _GetOverViewPrecipitation()

_Time1GUI()
Func _Time1GUI()
    GuiDelete($Time1GUI)
    GuiDelete($Time2GUI)
    GuiDelete($Time3GUI)
    GuiDelete($Time4GUI)
    $Time1GUI = GUICreate("", 150, 300, $Width-151, $Height-600, BitOR($WS_POPUP,$WS_BORDER), Default, WinGetHandle(AutoItWinGetTitle()))
    GuiSetFont(13)
    GUICtrlSetDefColor(0xFFFFFF)
    GUISetBkColor(0x000000)
    WinSetTrans($Time1GUI,"",200)
    GuiCtrlCreateLabel($OverViewTime[1],45,10,200,50)
    _GDIPlus_StartUp()
    $hImage   = _GDIPlus_ImageLoadFromFile(@ScriptDir & "/Images/Image1.png")
    $hGraphic = _GDIPlus_GraphicsCreateFromHWND($Time1GUI)
    GUIRegisterMsg($WM_PAINT, "Time1MY_WM_PAINT")
    $OverViewStatus[1] = "Mostly Cloudy / Windy"
    $String = _StringSize($OverViewStatus[1])
    $hLabel = GUICtrlCreateLabel($String[0],0,128, $String[2], $String[3])
;~  $OverViewStatus[1] = "Isolated T-Storms / Wind"
;~  $OverViewString = _ArrayToString($OverViewStatus)
;~  $OverViewStringSplit = StringSplit($OverViewString,"|",2)
;~  If (StringLen($OverViewStringSplit[1])) > 8 Then
;~  GuiCtrlCreateLabel($OverViewStatus[1],10,128,200,40)
;~  GuiCtrlSetFont(-1,10)
;~ ElseIf (StringLen($OverViewStringSplit[1])) < 8 Then
;~  GuiCtrlCreateLabel($OverViewStatus[1],28,128,200,40)
;~  EndIf
    GuiCtrlCreateLabel("Temperature",38,160,200,40)
    GuiCtrlCreateLabel($OverViewTemp[1] & "°F",64,185,200,40)
    GuiCtrlCreateLabel("Precipitation",34,220,200,40)
    GuiCtrlCreateLabel($OverViewPrecip[1],60,245,200,40)
    $ContextMenu = GuiCtrlCreateContextMenu()
    $Time1Item = GuiCtrlCreateMenuItem($OverViewTime[1], $ContextMenu)
    GUICtrlSetOnEvent($Time1Item, "_Time1GUI")
    $Time2Item = GuiCtrlCreateMenuItem($OverViewTime[2], $ContextMenu)
    GUICtrlSetOnEvent($Time2Item, "_Time2GUI")
    $Time3Item = GuiCtrlCreateMenuItem($OverViewTime[3], $ContextMenu)
    GUICtrlSetOnEvent($Time3Item, "_Time3GUI")
    $Time4Item = GuiCtrlCreateMenuItem($OverViewTime[4], $ContextMenu)
    GUICtrlSetOnEvent($Time4Item, "_Time4GUI")
    $RefreshItem = GuiCtrlCreateMenuItem("Refresh", $ContextMenu)
    GUICtrlSetOnEvent($RefreshItem, "_Refresh")
    $ExitItem = GuiCtrlCreateMenuItem("Close", $ContextMenu)
    GUICtrlSetOnEvent($ExitItem, "_Exit")
    DllCall("user32.dll", "hwnd", "SetParent", "hwnd", $Time1GUI, "hwnd", $h_Desktop_SysListView32)
    GuiSetState()
EndFunc

Func _Time2GUI()
    GuiDelete($Time1GUI)
    GuiDelete($Time2GUI)
    GuiDelete($Time3GUI)
    GuiDelete($Time4GUI)
    $Time2GUI = GUICreate("", 150, 300, $Width-151, $Height-600, BitOR($WS_POPUP,$WS_BORDER), Default, WinGetHandle(AutoItWinGetTitle()))
    GuiSetFont(13)
    GUICtrlSetDefColor(0xFFFFFF)
    GUISetBkColor(0x000000)
    WinSetTrans($Time2GUI,"",200)
    GuiCtrlCreateLabel($OverViewTime[2],45,10,200,50)
    _GDIPlus_StartUp()
    $hImage   = _GDIPlus_ImageLoadFromFile(@ScriptDir & "/Images/Image2.png")
    $hGraphic = _GDIPlus_GraphicsCreateFromHWND($Time2GUI)
    GUIRegisterMsg($WM_PAINT, "Time2MY_WM_PAINT")
    GuiCtrlCreateLabel($OverViewStatus[2],28,128,200,40)
    GuiCtrlSetFont(-1, 11)
    GuiCtrlCreateLabel("Temperature",38,160,200,40)
    GuiCtrlCreateLabel($OverViewTemp[2] & "°F",64,185,200,40)
    GuiCtrlCreateLabel("Precipitation",34,220,200,40)
    GuiCtrlCreateLabel($OverViewPrecip[2],60,245,200,40)
    $ContextMenu = GuiCtrlCreateContextMenu()
    $Time1Item = GuiCtrlCreateMenuItem($OverViewTime[1], $ContextMenu)
    GUICtrlSetOnEvent($Time1Item, "_Time1GUI")
    $Time2Item = GuiCtrlCreateMenuItem($OverViewTime[2], $ContextMenu)
    GUICtrlSetOnEvent($Time2Item, "_Time2GUI")
    $Time3Item = GuiCtrlCreateMenuItem($OverViewTime[3], $ContextMenu)
    GUICtrlSetOnEvent($Time3Item, "_Time3GUI")
    $Time4Item = GuiCtrlCreateMenuItem($OverViewTime[4], $ContextMenu)
    GUICtrlSetOnEvent($Time4Item, "_Time4GUI")
    $RefreshItem = GuiCtrlCreateMenuItem("Refresh", $ContextMenu)
    GUICtrlSetOnEvent($RefreshItem, "_Refresh")
    $ExitItem = GuiCtrlCreateMenuItem("Close", $ContextMenu)
    GUICtrlSetOnEvent($ExitItem, "_Exit")
    DllCall("user32.dll", "hwnd", "SetParent", "hwnd", $Time2GUI, "hwnd", $h_Desktop_SysListView32)
    GuiSetState()
EndFunc

Func _Time3GUI()
    GuiDelete($Time1GUI)
    GuiDelete($Time2GUI)
    GuiDelete($Time3GUI)
    GuiDelete($Time4GUI)
    $Time3GUI = GUICreate("", 150, 300, $Width-151, $Height-600, BitOR($WS_POPUP,$WS_BORDER), Default, WinGetHandle(AutoItWinGetTitle()))
    GuiSetFont(13)
    GUICtrlSetDefColor(0xFFFFFF)
    GUISetBkColor(0x000000)
    WinSetTrans($Time3GUI,"",200)
    GuiCtrlCreateLabel($OverViewTime[3],45,10,200,50)
    _GDIPlus_StartUp()
    $hImage   = _GDIPlus_ImageLoadFromFile(@ScriptDir & "/Images/Image3.png")
    $hGraphic = _GDIPlus_GraphicsCreateFromHWND($Time3GUI)
    GUIRegisterMsg($WM_PAINT, "Time3MY_WM_PAINT")
    GuiCtrlCreateLabel($OverViewStatus[3],28,128,200,40)
    GuiCtrlSetFont(-1, 11)
    GuiCtrlCreateLabel("Temperature",38,160,200,40)
    GuiCtrlCreateLabel($OverViewTemp[3] & "°F",64,185,200,40)
    GuiCtrlCreateLabel("Precipitation",34,220,200,40)
    GuiCtrlCreateLabel($OverViewPrecip[3],60,245,200,40)
    $ContextMenu = GuiCtrlCreateContextMenu()
    $Time1Item = GuiCtrlCreateMenuItem($OverViewTime[1], $ContextMenu)
    GUICtrlSetOnEvent($Time1Item, "_Time1GUI")
    $Time2Item = GuiCtrlCreateMenuItem($OverViewTime[2], $ContextMenu)
    GUICtrlSetOnEvent($Time2Item, "_Time2GUI")
    $Time3Item = GuiCtrlCreateMenuItem($OverViewTime[3], $ContextMenu)
    GUICtrlSetOnEvent($Time3Item, "_Time3GUI")
    $Time4Item = GuiCtrlCreateMenuItem($OverViewTime[4], $ContextMenu)
    GUICtrlSetOnEvent($Time4Item, "_Time4GUI")
    $RefreshItem = GuiCtrlCreateMenuItem("Refresh", $ContextMenu)
    GUICtrlSetOnEvent($RefreshItem, "_Refresh")
    $ExitItem = GuiCtrlCreateMenuItem("Close", $ContextMenu)
    GUICtrlSetOnEvent($ExitItem, "_Exit")
    DllCall("user32.dll", "hwnd", "SetParent", "hwnd", $Time3GUI, "hwnd", $h_Desktop_SysListView32)
    GuiSetState()
EndFunc

Func _Time4GUI()
    GuiDelete($Time1GUI)
    GuiDelete($Time2GUI)
    GuiDelete($Time3GUI)
    GuiDelete($Time4GUI)
    $Time4GUI = GUICreate("", 150, 300, $Width-151, $Height-600, BitOR($WS_POPUP,$WS_BORDER), Default, WinGetHandle(AutoItWinGetTitle()))
    GuiSetFont(13)
    GUICtrlSetDefColor(0xFFFFFF)
    GUISetBkColor(0x000000)
    WinSetTrans($Time4GUI,"",200)
    GuiCtrlCreateLabel($OverViewTime[4],25,10,200,20)
    _GDIPlus_StartUp()
    $hImage   = _GDIPlus_ImageLoadFromFile(@ScriptDir & "/Images/Image4.png")
    $hGraphic = _GDIPlus_GraphicsCreateFromHWND($Time4GUI)
    GUIRegisterMsg($WM_PAINT, "Time2MY_WM_PAINT")
    GuiCtrlCreateLabel($OverViewStatus[4],28,128,200,40)
    GuiCtrlSetFont(-1, 11)
    GuiCtrlCreateLabel("Temperature",38,160,200,40)
    GuiCtrlCreateLabel($OverViewTemp[4] & "°F",64,185,200,40)
    GuiCtrlCreateLabel("Precipitation",34,220,200,40)
    GuiCtrlCreateLabel($OverViewPrecip[4],60,245,200,40)
    $ContextMenu = GuiCtrlCreateContextMenu()
    $Time1Item = GuiCtrlCreateMenuItem($OverViewTime[1], $ContextMenu)
    GUICtrlSetOnEvent($Time1Item, "_Time1GUI")
    $Time2Item = GuiCtrlCreateMenuItem($OverViewTime[2], $ContextMenu)
    GUICtrlSetOnEvent($Time2Item, "_Time2GUI")
    $Time3Item = GuiCtrlCreateMenuItem($OverViewTime[3], $ContextMenu)
    GUICtrlSetOnEvent($Time3Item, "_Time3GUI")
    $Time4Item = GuiCtrlCreateMenuItem($OverViewTime[4], $ContextMenu)
    GUICtrlSetOnEvent($Time4Item, "_Time4GUI")
    $RefreshItem = GuiCtrlCreateMenuItem("Refresh", $ContextMenu)
    GUICtrlSetOnEvent($RefreshItem, "_Refresh")
    $ExitItem = GuiCtrlCreateMenuItem("Close", $ContextMenu)
    GUICtrlSetOnEvent($ExitItem, "_Exit")
    DllCall("user32.dll", "hwnd", "SetParent", "hwnd", $Time4GUI, "hwnd", $h_Desktop_SysListView32)
    GuiSetState()
EndFunc

Func _Quit()
    Exit
EndFunc

While 1
    Sleep(10)
WEnd


Func _GetDesktopHandle()
    $h_Desktop_SysListView32 = 0

    Local Const $hDwmApiDll = DllOpen("dwmapi.dll")
    Local $sChkAero = DllStructCreate("int;")
    DllCall($hDwmApiDll, "int", "DwmIsCompositionEnabled", "ptr", DllStructGetPtr($sChkAero))
    Local $aero_on = DllStructGetData($sChkAero, 1)

    If Not $aero_on Then
        $h_Desktop_SysListView32 = WinGetHandle("Program Manager")
        Return 1
    Else
        Local $hCBReg = DllCallbackRegister("_GetDesktopHandle_EnumChildWinProc", "hwnd", "hwnd;lparam")
        If $hCBReg = 0 Then Return SetError(2)
        DllCall("user32.dll", "int", "EnumChildWindows", "hwnd", _WinAPI_GetDesktopWindow(), "ptr", DllCallbackGetPtr($hCBReg), "lparam", 101)
        Local $iErr = @error
        DllCallbackFree($hCBReg)
        If $iErr Then
            Return SetError(3, $iErr, "")
        EndIf
        Return 2
    EndIf
EndFunc

Func _Refresh()
    _GetOverViewTime()
    _GetOverViewTemperature()
    _GetOverViewImages()
    _GetOverViewStatus()
    _GetOverViewPrecipitation()
    _Time1GUI()
EndFunc

Func _Exit()
_GDIPlus_GraphicsDispose($hGraphic)
_GDIPlus_ImageDispose($hImage)
_GDIPlus_ShutDown()
    Exit
EndFunc

Func Time1MY_WM_PAINT($hWnd, $Msg, $wParam, $lParam)
    _WinAPI_RedrawWindow($Time1GUI, 0, 0, $RDW_UPDATENOW)
    _GDIPlus_GraphicsDrawImage($hGraphic, $hImage, 13, 15)
    _WinAPI_RedrawWindow($Time1GUI, 0, 0, $RDW_VALIDATE)
    Return $GUI_RUNDEFMSG
EndFunc

Func Time2MY_WM_PAINT($hWnd, $Msg, $wParam, $lParam)
    _WinAPI_RedrawWindow($Time2GUI, 0, 0, $RDW_UPDATENOW)
    _GDIPlus_GraphicsDrawImage($hGraphic, $hImage, 28, 28)
    _WinAPI_RedrawWindow($Time2GUI, 0, 0, $RDW_VALIDATE)
    Return $GUI_RUNDEFMSG
EndFunc

Func Time3MY_WM_PAINT($hWnd, $Msg, $wParam, $lParam)
    _WinAPI_RedrawWindow($Time3GUI, 0, 0, $RDW_UPDATENOW)
    _GDIPlus_GraphicsDrawImage($hGraphic, $hImage, 28, 28)
    _WinAPI_RedrawWindow($Time3GUI, 0, 0, $RDW_VALIDATE)
    Return $GUI_RUNDEFMSG
EndFunc

Func Time4MY_WM_PAINT($hWnd, $Msg, $wParam, $lParam)
    _WinAPI_RedrawWindow($Time4GUI, 0, 0, $RDW_UPDATENOW)
    _GDIPlus_GraphicsDrawImage($hGraphic, $hImage, 28, 28)
    _WinAPI_RedrawWindow($Time4GUI, 0, 0, $RDW_VALIDATE)
    Return $GUI_RUNDEFMSG
EndFunc

UDF:

#include <array.au3>
#Include-Once

Global $OverViewTemp[10], $OverViewImage[5], $OverViewStatus[5], $OverViewPrecip[5], $OverViewTime[5]
Global $ZipCode, $RightNowImage, $TodayImage, $TonightImage, $TomorrowImage

Func _GetOverViewTime()
Global $sSource = BinaryToString(InetRead("http://www.weather.com/weather/today/" & $ZipCode))
For $i = 1 To 5
    If $i = 1 Then
        $Time1 = StringRegExp($sSource,'(?i)(?s)<span class="twc-forecast-when twc-none">(.*?)</span>',1)
        If @Error Then
            $Time1 = StringRegExp($sSource,'(?i)(?s)<span class="twc-forecast-when twc-block">(.*?)</span>',1)
        EndIf
    ElseIf $i = 2 Then
        $Time2 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-2 twc-forecast-when">(.*?)</td>',1)
    ElseIf $i = 3 Then
        $Time3 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-3 twc-forecast-when">(.*?)</td>',1)
    ElseIf $i = 4 Then
        $Time4 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-4 twc-forecast-when">(.*?)</td>',1)
    EndIf
Next
For $i = 1 To 4
    If $i = 1 Then
    $OverViewTime[1] = $Time1[0]
ElseIf $i = 2 Then
    $OverViewTime[2] = $Time2[0]
ElseIf $i = 3 Then
    $OverViewTime[3] = $Time3[0]
ElseIf $i = 4 Then
    $OverViewTime[4] = $Time4[0]
EndIf
Next
EndFunc

Func _GetOverViewTemperature()
Global $sSource = BinaryToString(InetRead("http://www.weather.com/weather/today/" & $ZipCode))
For $i = 1 To 5
    If $i = 1 Then
        $Temp1 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-1 twc-forecast-temperature"><strong>(.*?)&deg',1)
    ElseIf $i = 2 Then
        $Temp2 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-2 twc-forecast-temperature"><strong>(.*?)&deg',1)
    ElseIf $i = 3 Then
        $Temp3 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-3 twc-forecast-temperature"><strong>(.*?)&deg',1)
    ElseIf $i = 4 Then
        $Temp4 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-4 twc-forecast-temperature"><strong>(.*?)&deg',1)
    EndIf
Next
For $i = 1 To 4
    If $i = 1 Then
    $OverViewTemp[1] = $Temp1[0]
ElseIf $i = 2 Then
    $OverViewTemp[2] = $Temp2[0]
ElseIf $i = 3 Then
    $OverViewTemp[3] = $Temp3[0]
ElseIf $i = 4 Then
    $OverViewTemp[4] = $Temp4[0]
EndIf
Next
EndFunc

Func _GetOverViewImages()
    Global $sSource = BinaryToString(InetRead("http://www.weather.com/weather/today/" & $ZipCode))
$Image1 = StringRegExp($sSource, "(?i)(?m:^)\s*<img\ssrc=.+(http.+\.png).*column 1.*-->", 1)
$Image2 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-2 twc-forecast-icon"><a href="/weather/tenday/' & $ZipCode &'" from="today_daypartforecast_icon"><img src="(.*?)"',1)
$Image3 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-3 twc-forecast-icon"><a href="/weather/tenday/' & $ZipCode &'" from="today_daypartforecast_icon"><img src="(.*?)"',1)
$Image4 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-4 twc-forecast-icon"><a href="/weather/tenday/' & $ZipCode &'" from="today_daypartforecast_icon"><img src="(.*?)"',1)
For $i = 1 To 4
    If $i = 1 Then
    $OverViewImage[1] = $Image1[0]
ElseIf $i = 2 Then
    $OverViewImage[2] = $Image2[0]
ElseIf $i = 3 Then
    $OverViewImage[3] = $Image3[0]
ElseIf $i = 4 Then
    $OverViewImage[4] = $Image4[0]
EndIf
Next
For $i = 1 To 4
    If $i = 1 Then
        $RightNowImage = InetGet($OverViewImage[1], @ScriptDir & "\Images\Image1.png")
EndIf
    If $i = 2 Then
        $TodayImage = InetGet($OverViewImage[2], @ScriptDir & "\Images\Image2.png")
EndIf
    If $i = 3 Then
        $TonightImage = InetGet($OverViewImage[3], @ScriptDir & "\Images\Image3.png")
EndIf
    If $i = 4 Then
        $TomorrowImage = InetGet($OverViewImage[4], @ScriptDir & "\Images\Image4.png")
    EndIf
Next
EndFunc

Func _GetOverViewStatus()
    Global $sSource = BinaryToString(InetRead("http://www.weather.com/weather/today/" & $ZipCode))
    For $i = 1 To 4
    If $i = 1 Then
        $Status1 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-1">(.*?)</td>',1)
    ElseIf $i = 2 Then
        $Status2 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-2">(.*?)</td>',1)
    ElseIf $i = 3 Then
        $Status3 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-3">(.*?)</td>',1)
    ElseIf $i = 4 Then
        $Status4 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-4">(.*?)</td>',1)
    EndIf
Next
For $i = 1 To 4
    If $i = 1 Then
    $OverViewStatus[1] = $Status1[0]
ElseIf $i = 2 Then
    $OverViewStatus[2] = $Status2[0]
ElseIf $i = 3 Then
    $OverViewStatus[3] = $Status3[0]
ElseIf $i = 4 Then
    $OverViewStatus[4] = $Status4[0]
EndIf
Next
EndFunc

Func _GetOverViewPrecipitation()
    Global $sSource = BinaryToString(InetRead("http://www.weather.com/weather/today/" & $ZipCode))
    $PrecipForToday = StringRegExp($sSource,'(?i)(?s)<br>Precip:(.*?)</strong>',1)
    $PrecipString = _ArrayToString($PrecipForToday)
    $PrecipStringStrippedOfSpaces = StringStripWS($PrecipString,8)
    $Precip1Beta = StringReplace($PrecipStringStrippedOfSpaces, "<strong>", "")
    $Precip1 = StringReplace($Precip1Beta, "(est.)", "")
    $Precip2 = StringRegExp($sSource,'(?i)(?s)twc-clickable-dotted">Chance of Rain:</span><br><strong>(.*?)</strong></td>',1)
    If @Error Then
        $Precip2 = StringRegExp($sSource,'(?i)(?s)twc-clickable-dotted">Chance of Precip:</span><br><strong>(.*?)</strong></td>',1)
    EndIf
    $Precip3 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-3 twc-line-precip">Chance of Rain:<br><strong>(.*?)</strong></td>',1)
    If @Error Then
        $Precip3 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-3 twc-line-precip">Chance of Precip:<br><strong>(.*?)</strong></td>',1)
    EndIf
    $Precip4 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-4 twc-line-precip">Chance of Rain:<br><strong>(.*?)</strong></td>',1)
    If @Error Then
        $Precip4 = StringRegExp($sSource,'(?i)(?s)<td class="twc-col-4 twc-line-precip">Chance of Precip:<br><strong>(.*?)</strong></td>',1)
    EndIf
    For $i = 1 To 4
    If $i = 1 Then
    $OverViewPrecip[1] = $Precip1
ElseIf $i = 2 Then
    $OverViewPrecip[2] = $Precip2[0]
ElseIf $i = 3 Then
    $OverViewPrecip[3] = $Precip3[0]
ElseIf $i = 4 Then
    $OverViewPrecip[4] = $Precip4[0]
EndIf
Next
EndFunc
Edited by Damein

MCR.jpg?t=1286371579

Most recent sig. I made

Quick Launcher W/ Profiles Topic Movie Database Topic & Website | LiveStreamer Pro Website | YouTube Stand-Alone Playlist Manager: Topic | Weather Desktop Widget: Topic | Flash Memory Game: Topic | Volume Control With Mouse / iTunes Hotkeys: Topic | Weather program: Topic | Paws & Tales radio drama podcast mini-player: Topic | Quick Math Calculations: Topic

Link to comment
Share on other sites

  • Moderators

Damein,

You are setting the font size for all controls in your GUI to 13 with this:

GuiSetFont(13)

so you need to reflect that in the _StringSize function. You also need to set the maximum width that you will accept - in this case the width of your GUI. Your function call should therefore look like this:

$String = _StringSize($OverViewStatus[1], 13, Default, Default, "", 150)

This gives me a required label height ($String[3]) of 50 if I use "Mostly Cloudy / Windy" as the value.

Now comes your next problem - if you use this depth for the label it overlaps with the next label down. You could manage that by calculating the label heights first and then sizing the GUI as required and positioning the labels to fit. Or you could use the _StringSize function to calculate the font size needed to fit the string into a single line. Your choice. :unsure:

All clear? Please ask again if not. :>

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Alright, I think I got it now but now that I do I think its not what I was thinking it was x.X

I was under the impression this UDF would create a label out of the text provided to fit 100% always. If true, I guess I'm still doing something wrong because thats not happening.

MCR.jpg?t=1286371579

Most recent sig. I made

Quick Launcher W/ Profiles Topic Movie Database Topic & Website | LiveStreamer Pro Website | YouTube Stand-Alone Playlist Manager: Topic | Weather Desktop Widget: Topic | Flash Memory Game: Topic | Volume Control With Mouse / iTunes Hotkeys: Topic | Weather program: Topic | Paws & Tales radio drama podcast mini-player: Topic | Quick Math Calculations: Topic

Link to comment
Share on other sites

  • Moderators

Damein,

this UDF would create a label out of the text provided to fit 100% always

It does, but you have to give the correct parameters to do its work. :>

In particular the size, atrributes, weight and name of the font and the maximum width it can use. :unsure:

Remember that AutoIt cannot read your mind - you have to tell it what it is supposed to do! ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • 3 months later...

Hi Melba23,

I copied the UDF from what Damein posted and saved it as StringSize.au3 because I want to try your ExtMsgBox.au3

I get the following error when I do a SyntaxCheckProd:

+>10:48:27 Starting AutoIt3Wrapper v.2.0.1.24 Environment(Language:0409 Keyboard:00000409 OS:WIN_XP/Service Pack 3 CPU:X86 OS:X86)

>Running AU3Check (1.54.19.0) from:C:\Program Files\AutoIt3

C:\Program Files\AutoIt3\Include\ExtMsgBox.au3(281,139) : ERROR: StringSize(): undefined function.

Local $aLabel_Pos = StringSize($sText, $iEMB_Font_Size, Default, Default, $sEMB_Font_Name, $iMsg_Width_max - 20 - $iIcon_Reduction)

Could it be the UDF I copied is not correct?

Where can I get your original Stringsize.au3?

Thanks.

Link to comment
Share on other sites

Damien's post isn't the StringSize UDF, it's his own for his project. The StringSize UDF is in the first post in this thread, as they all usually are in the Example Scripts section.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

  • 2 weeks later...
  • Moderators

New version - 16 Aug 11

New:

New method to get the required font into the Display Context for sizing via GetTextExtentPoint32W. Default code (by trancexx :) ) or you can add the handle of your GUI to use that font directly.

The UDF did not correctly recognise TAB characters and so undersized lines containing them. Adding 1 to the $iAttrib paramter will expand tabs to "XXXXXXXX" before sizing the text - they are replaced before the text is returned. This might mean that the returned size is slightly too wide, but at least the line will fit! See the ExtMsgBox thread for an example showing this.

Changed:

One or two minor code changes (improvements I hope!).

Note that that these are non-scriptbreaking changes - unless you need to expand tabs you use StringSize just as before. I realise the use of $iAttrib to pass the "expand tab" is less that ideal, but it does prevent using another parameter. :)

New UDF and new examples in first post. :mellow:

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Wow! When I saw your post the other day I was a little excited of what was up your sleeve & where was this little gem (GetTextExtentPoint32W) hiding! :mellow:

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

guinness,

GetTextExtentPoint32W has been there since the early days of this UDF as it is is the only reliable way to size the text. The new code is that which determines the Device Context and the Font Handle (lines 84-117). :mellow:

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Apologies, seems I wasn't paying attention. :mellow:

UDF List:

 
_AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • 8 months later...

I'm working on a script that needs to get StringSize in order to set the size of a .jpg being created from a text variable ( my post is: ) and in my post someone pointed me to your StringSize post. It looks like it has the potential to help me with my problem, but I'm not sure how to calculate a maximum width with your StringSize script when my code is attempting to put my text output into a single line and base the width of that single line (no wrapping) on the pixel width of my text variable (Arial font set to size 600). Is there any way you could take a look at my code and let me know how (if possible) I could use your StringSize to give me the width variable I need to set in my .jpg output? I'd post my script here but I don’t want to spam your post with my script. You can see my post under

Any advice you could give me would be greatly appreciated.

Thanks,

TBWalker

Link to comment
Share on other sites

that's really a nice job , I didn't think I would get all these stumbles in my second day of scripting with autoIt , I'm having a problem of formatting the labels , it was partially solved when I used your UDF , but still get an error :

UICtrlCreateLabel($aSize[0], 40, 50+$height, $aSize[2], $aSize[3])
GUICtrlCreateLabel($aSize^ ERROR

the problem occurs when I try to create a label with the text resulting from clipget() , it results only when the clipget() has text with CRLF

i.e: trying to Ctrl+C 2 lines of code , and creating a label with that value results in the error written above

Link to comment
Share on other sites

  • Moderators

aurm,

Sorry for the delay in replying - I have been away for a few days. :)

The UDF works fine for me with strings containing @CRLF - even when they are returned from ClipGet. From where are you copying the text? Perhaps you are getting some additional characters in the string which are confusing the GetTextExtentPoint32W algorithm. ;)

Could you please try a clip content which causes you a problem with this script and see what errors are returned - perhaps that will let us see what is going on. :D

#include <GUIConstantsEx.au3>
#include <StringSize.au3>

$hGUI = GUICreate("Test", 500, 500)

$cButton = GUICtrlCreateButton("Run", 10, 10, 80, 30)

GUISetState()

While 1

    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $cButton
            $sData = ClipGet()
            $aRet = _StringSize($sData)
            If @error Then
                ConsoleWrite(@error & " - " & @extended & @CRLF)
            Else
                ConsoleWrite($aRet[0] & @CRLF)
            EndIf


    EndSwitch

WEnd

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Melba23 changed the title to StringSize - M23 - BugFix version 27 Dec 23

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...