Sign in to follow this  
Followers 0
DatMCEyeBall

How to use HTML tags in a rich edit control? - Almost Solved

8 posts in this topic

#1 ·  Posted (edited)

I am working on a script that loads data from a file and displays it with bold, highlighted etc. text.
The text looks something like this "This is <b>bold</b> text and this is <c=FF0000>red<c> text"
So how exactly would I go about doing this. (maybe some StringRegExp() magic)

NOTE: I want to load the text from a .txt file not a .rtf file.

I've tried searching and found nothing of intrest.

Edited by DatMCEyeBall

"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

I've done this sort of thing in Salesforce to populate a rich edit control. What I found in working with the SFDC rich edit control is when I simply sent a string to the control the HTML code did not work as expected. When I used a formula then a field update via workflow to update the rich edit control, the HTML string then performed as expected in the rich edit control.

Loading the text from a text file is no big deal - your simply capturing the string you need and sending it to the rich edit control. The trick is getting the control to understand the string your sending is data for the control to interpret, not just a string to insert as plain text and have the rich edit control format the text to display it exactly as typed.

Whats the name of the application? If I knew what it was I could see what needs to be done with it.

Edited by YogiBear

Share this post


Link to post
Share on other sites

It's not an application, it's just a simple script I am making to display HTML highlighted code - ya know just in case I need it later.

I came up with a simple way to make the rich edit control "understand" what was being sent

;~ Copy and paste the following into the Input box to see it work
;~ <b>using</b> <c=FF0000>lots</c> of <s>tags</s>. This <u>text</u> is <s>tagged</s> tag-less. I <f=Times New Roman,9>am</f> <i>Italic</i> with a <h=FFFF00>highlighted</h> background.
#include <GuiRichEdit.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <Color.au3>
#include <Array.au3>

$hGui = GUICreate("Example of using HTML tags", 320, 200, -1, -1)
$hRichEdit = _GUICtrlRichEdit_Create($hGui, "", 10, 10, 300, 150, _
        BitOR($ES_MULTILINE, $WS_VSCROLL, $ES_AUTOVSCROLL))
$hInput = GUICtrlCreateInput("", 10, 170, 300, 17)
GUICtrlSetState($hInput, $GUI_FOCUS)
GUISetState()

While 1
    $iMsg = GUIGetMsg()
    If $iMsg = $GUI_EVENT_CLOSE Then
        _GUICtrlRichEdit_Destroy($hRichEdit) ; needed unless script crashes
        Exit
    EndIf
    If $iMsg = $hInput Then
        _GUICtrlRichEdit_AppendText($hRichEdit, _RemoveTags(GUICtrlRead($hInput)) & @CRLF)
        _HighLight(GUICtrlRead($hInput))
        GUICtrlSetData($hInput, "")
        GUICtrlSetState($hInput, $GUI_FOCUS)
    EndIf
WEnd

Func _RemoveTags($InText)
    $NewText1 = StringRegExpReplace($InText, '<b>(.*?)</b>', "$1")
    $NewText1 = StringRegExpReplace($NewText1, '<i>(.*?)</i>', "$1")
    $NewText1 = StringRegExpReplace($NewText1, '<u>(.*?)</u>', "$1")
    $NewText1 = StringRegExpReplace($NewText1, '<s>(.*?)</s>', "$1")
    $NewText1 = StringRegExpReplace($NewText1, '<(?i)c=(?:.*?)>(.*?)</(?i)c>', "$1")
    $NewText1 = StringRegExpReplace($NewText1, '<(?i)h=(?:.*?)>(.*?)</(?i)h>', "$1")
    $NewText1 = StringRegExpReplace($NewText1, '<(?i)f=(?:.*?)>(.*?)</(?i)f>', "$1")
    Return $NewText1
EndFunc   ;==>_RemoveTags

Func _HighLight($sText)
    _SetAttrib($sText, '<(?i)b>(.*?)</(?i)b>', "+bo") ;Bold
    _SetAttrib($sText, '<(?i)i>(.*?)</(?i)i>', "+it") ;Italics
    _SetAttrib($sText, '<(?i)u>(.*?)</(?i)u>', "+un") ;Underline
    _SetAttrib($sText, '<(?i)s>(.*?)</(?i)s>', "+st") ;Strike-Out

    $Search = _GUICtrlRichEdit_GetText($hRichEdit)
    $Pos = StringInStr($Search, $sText, 1, -1); - 1

    $nOffset = 1
    While 1
        $RegExp = StringRegExp($sText, '<(?i)c=(.*?)>(.*?)</(?i)c>', 1, $nOffset)
        If @error = 0 Then
            $nOffset = @extended
        Else
            ExitLoop
        EndIf

        $st = (StringInStr($Search, $RegExp[1]) - 1) + $Pos
        $end = StringLen($RegExp[1]) + $st

        _GUICtrlRichEdit_SetSel($hRichEdit, $st, $end, True)
        $ColArray = _ColorGetRGB("0x" & $RegExp[0])

        _GUICtrlRichEdit_SetCharColor($hRichEdit, _ColorSetCOLORREF($ColArray))
        _GUICtrlRichEdit_Deselect($hRichEdit)
    WEnd

    $nOffset = 1
    While 1
        $RegExp = StringRegExp($sText, '<(?i)h=(.*?)>(.*?)</(?i)h>', 1, $nOffset)
        If @error = 0 Then
            $nOffset = @extended
        Else
            ExitLoop
        EndIf

        $st = (StringInStr($Search, $RegExp[1]) - 1) + $Pos
        $end = StringLen($RegExp[1]) + $st

        _GUICtrlRichEdit_SetSel($hRichEdit, $st, $end, True)
        $ColArray = _ColorGetRGB("0x" & $RegExp[0])

        _GUICtrlRichEdit_SetCharBkColor($hRichEdit, _ColorSetCOLORREF($ColArray))
        _GUICtrlRichEdit_Deselect($hRichEdit)
    WEnd

    $nOffset = 1
    While 1
        $RegExp = StringRegExp($sText, '<(?i)f=(.*?)>(.*?)</(?i)f>', 1, $nOffset)
        If @error = 0 Then
            $nOffset = @extended
        Else
            ExitLoop
        EndIf

        $st = (StringInStr($Search, $RegExp[1]) - 1) + $Pos
        $end = StringLen($RegExp[1]) + $st

        _GUICtrlRichEdit_SetSel($hRichEdit, $st, $end, True)

        $PointFont = StringSplit($RegExp[0], ",")
        If $PointFont[0] <> 2 Then ContinueLoop
        _GUICtrlRichEdit_SetFont($hRichEdit, $PointFont[2], $PointFont[1])

        _GUICtrlRichEdit_Deselect($hRichEdit)
    WEnd
EndFunc   ;==>_HighLight

Func _SetAttrib($Text, $Patt, $style)
    $Search = _GUICtrlRichEdit_GetText($hRichEdit)
    $Pos = StringInStr($Search, $Text, 1, -1) - 1

    $nOffset = 1
    While 1
        $RegExp = StringRegExp($Text, $Patt, 1, $nOffset)
        If @error = 0 Then
            $nOffset = @extended
        Else
            ExitLoop
        EndIf

        For $x = 0 To UBound($RegExp) - 1
            $st = (StringInStr($Search, $RegExp[$x]) - 1) + $Pos
            $end = StringLen($RegExp[$x]) + $st

            _GUICtrlRichEdit_SetSel($hRichEdit, $st, $end, True)
            _GUICtrlRichEdit_SetCharAttributes($hRichEdit, $style)
            _GUICtrlRichEdit_Deselect($hRichEdit)
        Next
    WEnd
EndFunc   ;==>_SetAttrib

It wroks but fails when I enter "I enjoy this <c=FF000>en</c><c=00FF00>jo</c><c=0000FF>ya</c>ble script."

It ends up changing the colours of the wrong chars.


"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Share this post


Link to post
Share on other sites

Does it seek for any support to nesting. If not the coding could be easy.. :P


My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

Does it seek for any support to nesting. If not the coding could be easy.. :P

No, It doesn't, All it has to do is recognize HTML tags and apply the appropriate style(bold, colored text, colored BK etc)  

I found in some cases a rich edit control does not recognize certain HTML switches. 

True dat.


"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

Here is an example

;tags supported without nesting.

;Test with the following text.
;play with it. <it> this is italics</it><IT></IT>. Following is <bo>Bold</bo><BO></BO>. <un>Underlined</un><UN> and </UN><st>striked</st>. The end is also striked since its appended w/o switching off the attribute.
;<fo=MS Shell Dlg,10>This is the Default Font of my OS</fo><fo=Arial,8.5>This is in Arial with default Size</fo>
;Now Colors <ch=F0F0F0,0F0F0F>Colored Text with Colored Background</ch><ch=FFFFFF,0>reverting to default</ch>

;Instructions
#cs Tags which can be used.
    <bo> - Bold
    <it> - italics
    <st> - striked through
    <un> - underlined
    use capitals for switching off the attribute.
    The above would even work even if their is no innerText enclosed within the tags.

    A comma(,) is necessary in the following tags.
    <ch=ABCDEF,UVWXYZ> - Color(ABCDEF) and Background Color(UVWXYZ)
    <fo=ABCD EF GH,XX> - FontName(ABCD EF GH) and PointSize(XX)
    
#ce

;if a tag is not closed error is caused and nothing is appended.
;if no tag is present the text is appended.
;

;spaces not allowed inside the tag content except for fontname.
;let me know if nesting or anything else is required.

#include <GuiRichEdit.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <Color.au3>
#include <Array.au3>
#include <Misc.au3>

Global $hRichEdit

Func _HighLight($s_Append)

    If StringRegExp($s_Append, "[<>]") = 0 Then Return _GUICtrlRichEdit_AppendText($hRichEdit, $s_Append)
    $iOffset = StringLen(_GUICtrlRichEdit_GetText($hRichEdit))

    ;the following is only for attributes
    While 1

        $aInfo_Regex = StringRegExp($s_Append, '^(?is)(.*?)<(bo|it|st|un)>(.*?)</\2>', 4) ;Bold, Italics, Strick-Out or Underline
        If @error Then ExitLoop

        For $n = 0 To UBound($aInfo_Regex) - 1
            $Temp = $aInfo_Regex[$n]

            ;The full match is in 0th index.
            ;the text preceding the tag is in 1st index.
            ;the tag name is in 2nd index.
            ;the enclosed text is in 3rd index.

            ;Append the required text
            _GUICtrlRichEdit_AppendText($hRichEdit, $Temp[1] & $Temp[3])

            ;set the selection for the text to be highlighted.
            _GUICtrlRichEdit_SetSel($hRichEdit, $iOffset + StringLen($Temp[1]), $iOffset + StringLen($Temp[1] & $Temp[3]), True)

            _GUICtrlRichEdit_SetCharAttributes($hRichEdit, _Iif(StringIsLower($Temp[2]), "+", "-") & $Temp[2])
            _GUICtrlRichEdit_Deselect($hRichEdit)

            $s_Append = StringMid($s_Append, StringLen($Temp[0]) + 1)
            $iOffset += StringLen($Temp[1] & $Temp[3])
        Next

    WEnd

    If StringRegExp($s_Append, "[<>]") = 0 Then Return _GUICtrlRichEdit_AppendText($hRichEdit, $s_Append)

    $iOffset = StringLen(_GUICtrlRichEdit_GetText($hRichEdit))
    ;for colors bkcolor and font(with size).

    While 1
        $aInfo_Regex = StringRegExp($s_Append, '(?is)^(.*?)<(ch|fo)=([^,]*),(.*?)>(.*?)</\2>', 4)
        If @error Then ExitLoop

        For $n = 0 To UBound($aInfo_Regex) - 1
            $Temp = $aInfo_Regex[$n]

            ;The full match is in 0th index.
            ;The preceding text is in 1st index.
            ;the tag name is in 2nd index.
            ;the first parameter is in the 3rd index.
            ;the second parameter is in the 4th index.
            ;the enclosed text is in the 5th index.
;~          _ArrayDisplay($Temp)

            ;Append the required text
            _GUICtrlRichEdit_AppendText($hRichEdit, $Temp[1] & $Temp[5])

            ;set the selection for the text to be highlighted.
            _GUICtrlRichEdit_SetSel($hRichEdit, $iOffset + StringLen($Temp[1]), $iOffset + StringLen($Temp[1] & $Temp[5]), True)



            Switch $Temp[2]

                Case "ch" ;color

                    If $Temp[3] Then
                        $ColArray = _ColorGetRGB("0x" & $Temp[3])
                        _GUICtrlRichEdit_SetCharColor($hRichEdit, _ColorSetCOLORREF($ColArray))
                    EndIf

                    If $Temp[4] Then
                        $ColArray = _ColorGetRGB("0x" & $Temp[4])
                        _GUICtrlRichEdit_SetCharBkColor($hRichEdit, _ColorSetCOLORREF($ColArray))
                    EndIf

                Case "fo" ;font

                    MsgBox(0,0,_GUICtrlRichEdit_SetFont($hRichEdit, $Temp[4], $Temp[3]))

            EndSwitch


            _GUICtrlRichEdit_Deselect($hRichEdit)

            $s_Append = StringMid($s_Append, StringLen($Temp[0]) + 1)
            $iOffset += StringLen($Temp[4])
        Next

    WEnd

    Return _GUICtrlRichEdit_AppendText($hRichEdit, $s_Append)

EndFunc   ;==>_HighLight

$hGui = GUICreate("Example of using HTML tags", 320, 200, -1, -1)

$hRichEdit = _GUICtrlRichEdit_Create($hGui, "", 10, 10, 300, 150, _
        BitOR($ES_MULTILINE, $WS_VSCROLL, $ES_AUTOVSCROLL))

$hInput = GUICtrlCreateInput("", 10, 170, 300, 17)

GUICtrlSetState($hInput, $GUI_FOCUS)
GUISetState()

;our main loop
While True

    Switch GUIGetMsg()

        Case $GUI_EVENT_CLOSE

            _GUICtrlRichEdit_Destroy($hRichEdit) ; needed unless script crashes
            Exit

        Case $hInput

            ;highlight...
            _HighLight(GUICtrlRead($hInput))

            ;revert the focus back to the Input.
            GUICtrlSetData($hInput, "")
            GUICtrlSetState($hInput, $GUI_FOCUS)

    EndSwitch

WEnd

The FontName and Color(BkColor) part is still buggy. I will soon fix it. Part with attributes work very nice...

Regards :)

Edited by PhoenixXL

My code:

PredictText: Predict Text of an Edit Control Like Scite. Remote Gmail: Execute your Scripts through Gmail. StringRegExp:Share and learn RegExp.

Run As System: A command line wrapper around PSEXEC.exe to execute your apps scripts as System (LSA). Database: An easier approach for _SQ_LITE beginners.

MathsEx: A UDF for Fractions and LCM, GCF/HCF. FloatingText: An UDF for make your text floating. Clipboard Extendor: A clipboard monitoring tool. 

Custom ScrollBar: Scroll Bar made with GDI+, user can use bitmaps instead. RestrictEdit_SRE: Restrict text in an Edit Control through a Regular Expression.

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

@PhoenixXL - Your script is perfect for what I need it for, which btw is a (slightly)fancy chat script.

NOTE: It's not actually a "chat" script yet - I'm still working on that.

EDIT:

Here's a screenshot:

post-79729-0-42859900-1372439604_thumb.p

Edited by DatMCEyeBall

"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Share this post


Link to post
Share on other sites

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
Sign in to follow this  
Followers 0

  • Similar Content

    • loganizzi
      By loganizzi
      If you look at the help file for the above command, you'll see that it states that it only works for certain zoom values (100 and 200 to 6400).   I assume that this is due to an issue in an MSDN library that the command relies on.
      After doing some investigating, I noticed that the GUIRichEdit.au3 library file contains the following code:
      ; #FUNCTION# ==================================================================================================================== ; Authors........: Chris Haslam (c.haslam) ; Modified ......: ; =============================================================================================================================== Func _GUICtrlRichEdit_SetZoom($hWnd, $iPercent) If Not _WinAPI_IsClassName($hWnd, $__g_sRTFClassName) Then Return SetError(101, 0, False) If Not __GCR_IsNumeric($iPercent, ">0") Then Return SetError(1021, 0, False) Local $iNumerator, $iDenominator Select Case Not ($iPercent = 100 Or ($iPercent >= 200 And $iPercent < 6400)) Return SetError(1022, 0, False) Case $iPercent >= 100 $iNumerator = 10000 $iDenominator = 10000 / ($iPercent / 100) Case Else $iNumerator = 10000 * ($iPercent / 100) $iDenominator = 10000 EndSelect Return _SendMessage($hWnd, $EM_SETZOOM, $iNumerator, $iDenominator) <> 0 EndFunc ;==>_GUICtrlRichEdit_SetZoom Which ensures that values are only within the bounds specified in the help file.    I found that if I comment out the portion of the code that limits the values, the function works fine for most (if not all) values.   I changed the code in the library file to this by simply commenting out the restricting lines of code:
      ; #FUNCTION# ==================================================================================================================== ; Authors........: Chris Haslam (c.haslam) ; Modified ......: ; =============================================================================================================================== Func _GUICtrlRichEdit_SetZoom($hWnd, $iPercent) If Not _WinAPI_IsClassName($hWnd, $__g_sRTFClassName) Then Return SetError(101, 0, False) If Not __GCR_IsNumeric($iPercent, ">0") Then Return SetError(1021, 0, False) Local $iNumerator, $iDenominator Select ; Case Not ($iPercent = 100 Or ($iPercent >= 200 And $iPercent < 6400)) ; Return SetError(1022, 0, False) Case $iPercent >= 100 $iNumerator = 10000 $iDenominator = 10000 / ($iPercent / 100) Case Else $iNumerator = 10000 * ($iPercent / 100) $iDenominator = 10000 EndSelect Return _SendMessage($hWnd, $EM_SETZOOM, $iNumerator, $iDenominator) <> 0 EndFunc ;==>_GUICtrlRichEdit_SetZoom  
      I assume whatever windows bug existed at the time this was created, no longer exists so there is no need to restrict the values.   
      Just wanted to point this out if anyone else is using this part of the library and required this functionality like I did.
       
    • AndreyS
      By AndreyS
      Tell me, please, how to set / change the cursor over RichEdit (created with _GUICtrlRichEdit_Create)?
    • StMaSi
      By StMaSi
      Two questions...
      When presenting a form containing a richedit control, is there any way to make the displayed text, within said richedit control, non-selectable?
      In addition, is there any way to hide the vertical line cursor, within said richedit control?
      Thanx.
    • TheSaint
      By TheSaint
      I've finally come up with some simple solutions for dragging & dropping a URL onto a control.
      There have been many requests here for this over the years.
      I do have an issue though, with my second code example solution as is mentioned here.
      The issue relates to working in Win 7 (and no doubt newer Windows).
      As I state there, failure is no doubt due to 'MSCOMCT2.OCX' missing from the System32 folder, at the very least.
      Not sure if it would be wise to just dump 'MSCOMCT2.OCX' from WinXP into the Win 7 System32 folder. I expect not.
      I imagine there is a better solution available in Win 7. Maybe a different OCX file, and perhaps a different Class of object etc.
      Any help would be greatly appreciated.
      Code is here (second example).
      EDIT
      Okay, I have rediscovered that 'MSCOMCT2.OCX' is a VB6 ActiveX control. So while I could dig up a copy and register it, that would probably not be helpful to everyone.
      And registering it didn't help. Possibly other dependencies are also needed?
      When running the script, it is clear going by the error reported, that Object is not being created.
    • AndreyS
      By AndreyS
      Please tell me, who knows how to apply and cancel styles in RTF?
      The following code does not work:
      #include <GuiRichEdit.au3> #include <WindowsConstants.au3> $hGUI = GUICreate("RichEdit Style", 500, 500, -1, -1) $hRichEdit = _GUICtrlRichEdit_Create($hGui, "Test", 20,40,460,400) GUISetState(@SW_SHOW, $hGUI) Sleep(3000) GUICtrlSetStyle($hRichEdit, $ES_RIGHT) Sleep(3000) GUICtrlSetStyle($hRichEdit, -1) Sleep(3000) Thanks!