SetClipboardHTML()

Post your working scripts, libraries and tools
User avatar
SKAN
Posts: 1427
Joined: 29 Sep 2013, 16:58

SetClipboardHTML()

06 Sep 2020, 05:15

SetClipboardHTML(HtmlBody[, HtmlHead, AltText])
Sets CF_HTML data in clipboard which can then be pasted with Ctrl+v
Sample: SetClipboardHTML("<div><b>Welcome to AutoHotkey</b></div>",, "Welcome to AutoHotkey")

Parameters:
 
  • HtmlBody : Body of the HTML, without <body></body> tags. Paste will work only in html capable input.
  • HtmlHead : Optional Head content of the HTML, without <head></head> tags.
    You may use this for limited CSS styling with supported editors like MS Word.
    For browser input (Gmail/YahooMail etc.), you may use limited inline styling in Body.
  • AltText : Optional alternative (unicode) text for html incapable editors like Notepad, PSPad etc.
 
 
Example: This following is a modified version of intro example given in docs under HotStrings.

Code: Select all

#NoEnv
#SingleInstance, Force
Hotstring(":*X:]d", "DatePaste")
Return

DatePaste:
  FormatTime, DTH,, '<div><i>'dddd'</i>', '<b>'dd-MMM-yyyy'</b>' h:mm tt'</div>'
  FormatTime, DTT,, dddd, dd-MMM-yyyy h:mm tt
  SetClipboardHTML(DTH,, DTT)
  SendInput ^v
Return
 
 
The function
 

Code: Select all

SetClipboardHTML(HtmlBody, HtmlHead:="", AltText:="") {       ; v0.67 by SKAN on D393/D42B
Local  F, Html, pMem, Bytes, hMemHTM:=0, hMemTXT:=0, Res1:=1, Res2:=1   ; @ tiny.cc/t80706
Static CF_UNICODETEXT:=13,   CFID:=DllCall("RegisterClipboardFormat", "Str","HTML Format")

  If ! DllCall("OpenClipboard", "Ptr",A_ScriptHwnd)
    Return 0
  Else DllCall("EmptyClipboard")

  If (HtmlBody!="")
  {
      Html     := "Version:0.9`r`nStartHTML:00000000`r`nEndHTML:00000000`r`nStartFragment"
               . ":00000000`r`nEndFragment:00000000`r`n<!DOCTYPE>`r`n<html>`r`n<head>`r`n"
                         . HtmlHead . "`r`n</head>`r`n<body>`r`n<!--StartFragment -->`r`n"
                              . HtmlBody . "`r`n<!--EndFragment -->`r`n</body>`r`n</html>"

      Bytes    := StrPut(Html, "utf-8")
      hMemHTM  := DllCall("GlobalAlloc", "Int",0x42, "Ptr",Bytes+4, "Ptr")
      pMem     := DllCall("GlobalLock", "Ptr",hMemHTM, "Ptr")
      StrPut(Html, pMem, Bytes, "utf-8")

      F := DllCall("Shlwapi.dll\StrStrA", "Ptr",pMem, "AStr","<html>", "Ptr") - pMem
      StrPut(Format("{:08}", F), pMem+23, 8, "utf-8")
      F := DllCall("Shlwapi.dll\StrStrA", "Ptr",pMem, "AStr","</html>", "Ptr") - pMem
      StrPut(Format("{:08}", F), pMem+41, 8, "utf-8")
      F := DllCall("Shlwapi.dll\StrStrA", "Ptr",pMem, "AStr","<!--StartFra", "Ptr") - pMem
      StrPut(Format("{:08}", F), pMem+65, 8, "utf-8")
      F := DllCall("Shlwapi.dll\StrStrA", "Ptr",pMem, "AStr","<!--EndFragm", "Ptr") - pMem
      StrPut(Format("{:08}", F), pMem+87, 8, "utf-8")

      DllCall("GlobalUnlock", "Ptr",hMemHTM)
      Res1  := DllCall("SetClipboardData", "Int",CFID, "Ptr",hMemHTM)
  }

  If (AltText!="")
  {
      Bytes    := StrPut(AltText, "utf-16")
      hMemTXT  := DllCall("GlobalAlloc", "Int",0x42, "Ptr",(Bytes*2)+8, "Ptr")
      pMem     := DllCall("GlobalLock", "Ptr",hMemTXT, "Ptr")
      StrPut(AltText, pMem, Bytes, "utf-16")
      DllCall("GlobalUnlock", "Ptr",hMemTXT)
      Res2  := DllCall("SetClipboardData", "Int",CF_UNICODETEXT, "Ptr",hMemTXT)
  }

  DllCall("CloseClipboard")
  hMemHTM := hMemHTM ? DllCall("GlobalFree", "Ptr",hMemHTM) : 0

Return (Res1 & Res2)
}
My Scripts and Functions: V1  V2
User avatar
Joe Glines
Posts: 768
Joined: 30 Sep 2013, 20:49
Facebook: https://www.facebook.com/theAutomatorGuru/
Google: https://plus.google.com/105328929654286634910
GitHub: joetazz
Location: Dallas
Contact:

Re: SetClipboardHTML()

19 Jan 2021, 14:52

Thanks @SKAN! As someone who loves HotStrings, It's great to be able to have HTML format as a replacement! I'm going to mention it on today's AutoHotkey webinar as the script highlight! :)
Sign-up for the 🅰️HK Newsletter

Find & Click AutoHotkey syntax writer Automate my Task :clap:
AHK Tutorials:Web Scraping | AHK Studio | Webservice APIs | AHK and Excel | Chrome | RegEx | Functions
Training: AHK Webinars Courses on AutoHotkey :ugeek:
YouTube
How-to: Create a shortcut that automatically
logs in to any website

:thumbup: Quick Access Popup, the powerful Windows folders, apps and documents launcher!
User avatar
Joe Glines
Posts: 768
Joined: 30 Sep 2013, 20:49
Facebook: https://www.facebook.com/theAutomatorGuru/
Google: https://plus.google.com/105328929654286634910
GitHub: joetazz
Location: Dallas
Contact:

Re: SetClipboardHTML()

02 Feb 2021, 21:57

@SKAN
Hi SKAN,
I really loved your script but I wanted to be able to save/restore the clipboard so I wrapped it with another function.
Unfortunately it isn't always setting the html content correctly. I tried playing with the sleeps on my end but am not sure what's causing the issue. At 6:15 I show an example of it "breaking".

If you have any thoughts, I'd love to hear them... Again, thank you for your code!

Code: Select all


::ta.::
HTMLHotstring("<a href='https://the-automator.com'>the-<span style='color:red'>Automator</span></a>",HTMLHead,"the-Automator.com",1)
return

HTMLHotstring(HTMLBody,HTMLHead,AltText,RestoreClipboard:=1){
	if (RestoreClipboard)
		ClipBackup:=ClipboardAll ;backup clipboard
	Clipboard:="" ;Blank the clipboard so can use ClipWait later
	SetClipboardHTML(HTMLBody,HTMLHead,AltText) ;Call function
	ClipWait,2 ;Wait up to 2 seconds for clipboard to have something.
	if ErrorLevel 	{ ;If nothing gets put onto clipboard
		MsgBox, Nothing was put in the clipboard`n`nRestoring original content & exiting ;explain something went wrong
		Clipboard:=ClipBackup ;restore clipboard to original content		
		return False
	}
	SendInput, ^v ;Send Control+V / Paste 
	if (RestoreClipboard){
		sleep, 100 ;needed to make sure pasted happens before restoring clipboard
		Clipboard:=ClipBackup ;restore clipboard to original content	
	}
	Return True
}

Sign-up for the 🅰️HK Newsletter

Find & Click AutoHotkey syntax writer Automate my Task :clap:
AHK Tutorials:Web Scraping | AHK Studio | Webservice APIs | AHK and Excel | Chrome | RegEx | Functions
Training: AHK Webinars Courses on AutoHotkey :ugeek:
YouTube
How-to: Create a shortcut that automatically
logs in to any website

:thumbup: Quick Access Popup, the powerful Windows folders, apps and documents launcher!
User avatar
rommmcek
Posts: 1406
Joined: 15 Aug 2014, 15:18

Re: SetClipboardHTML()

06 Feb 2021, 20:39

This works for me:

Code: Select all

DatePaste:
  ClipBackup:= ClipboardAll
  FormatTime, DTH,, '<div><i>'dddd'</i>', '<b>'dd-MMM-yyyy'</b>' h:mm tt'</div>'
  FormatTime, DTT,, dddd, dd-MMM-yyyy h:mm tt
  SetClipboardHTML(DTH,, DTT)
  SendInput ^v
  Sleep, 150
  while DllCall("user32\GetOpenClipboardWindow", "Ptr")
     Sleep, 150
  Clipboard:= ClipBackUp
Return
[Edit]: Putting "Wait for Clipboard" before Paste too, increases reliability further more.
[Edit2]: Not needed anymore due to fix by SKAN (thanks to report by tdalon).
Last edited by rommmcek on 10 Feb 2021, 17:15, edited 2 times in total.
User avatar
Joe Glines
Posts: 768
Joined: 30 Sep 2013, 20:49
Facebook: https://www.facebook.com/theAutomatorGuru/
Google: https://plus.google.com/105328929654286634910
GitHub: joetazz
Location: Dallas
Contact:

Re: SetClipboardHTML()

08 Feb 2021, 11:25

@rommmcekThanks! I'll play with it some more later this week.
Sign-up for the 🅰️HK Newsletter

Find & Click AutoHotkey syntax writer Automate my Task :clap:
AHK Tutorials:Web Scraping | AHK Studio | Webservice APIs | AHK and Excel | Chrome | RegEx | Functions
Training: AHK Webinars Courses on AutoHotkey :ugeek:
YouTube
How-to: Create a shortcut that automatically
logs in to any website

:thumbup: Quick Access Popup, the powerful Windows folders, apps and documents launcher!
User avatar
tdalon
Posts: 32
Joined: 21 Apr 2017, 07:19
GitHub: tdalon
Location: Germany
Contact:

Re: SetClipboardHTML()

09 Feb 2021, 01:32

This is amazing. Thanks @skan.
Also the hint by @rommmcek looks like I will get rid of these timing issue.
I was using WinClip https tdalon.blogspot.com /2020/02/autohotkey-clipboard-handling.html (Broken Link for safety) in the past but it has some issues.
Could you also provide a GetClipboardHTML function?

You can find my Clip library wrapping these functions here https://github.com/tdalon/ahk/blob/master/Lib/Clip.ahk.

Simple example of Hotstring using it:

Code: Select all

::teamsme:: ; Teams Me Chat Link (rtf)
sText = Chat with me in Teams
sLink :=  "https://teams.microsoft.com/l/chat/0/0?users="  
Clip_PasteHtml(sLink,sText,True)	
return
[Mod edit: [code][/code] tags added.]
Last edited by gregster on 09 Feb 2021, 01:45, edited 1 time in total.
Reason: Personal email address removed from public view.
User avatar
tdalon
Posts: 32
Joined: 21 Apr 2017, 07:19
GitHub: tdalon
Location: Germany
Contact:

Re: SetClipboardHTML()

10 Feb 2021, 14:24

@SKAN
If you run the function and immediately access the clipboard e.g. sClip := Clipboard
AutoHotkey will crash on Error: GlobalLock.
It seems the function does not complete with the clipboard being accessible. :(
User avatar
SKAN
Posts: 1427
Joined: 29 Sep 2013, 16:58

Re: SetClipboardHTML()

10 Feb 2021, 16:38

tdalon wrote:
10 Feb 2021, 14:24
@SKAN
If you run the function and immediately access the clipboard e.g. sClip := Clipboard
AutoHotkey will crash on Error: GlobalLock.
It seems the function does not complete with the clipboard being accessible. :(
Thanks for reporting this. 👍

Allocated (Global) memory for CF_UNICODETEXT shouldn't be freed by the function and let the OS do it. Ref: MSDN
While this doesn't seem to be a problem with AHK-ANSI, Unicode version crashes.
:arrow: This has been fixed in v0.67
User avatar
rommmcek
Posts: 1406
Joined: 15 Aug 2014, 15:18

Re: SetClipboardHTML()

10 Feb 2021, 17:12

That's why I proposed "Wait for Clipboard" before paste too, now redundant! Thanks to both of you!
valuex
Posts: 14
Joined: 01 Nov 2014, 08:17

Re: SetClipboardHTML()

13 Feb 2021, 08:01

@SKAN
It seems not going well with base64 image. Here is my case.
Any comment will be appreciated.

Code: Select all

   html=
    (       
        <img src="data:image/jpeg;charset=utf-8;base64, %base64string%">
        <p> description about the image</p>           
    )
    SetClipboardHTML( html )    
while the base64string is as following,
/9j/4AAQSkZJRgABAQEAkACQAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS
Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ
CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy
MjIyMjIyMjIyMjIyMjL/wAARCAAvAIYDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEA
AAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIh
MUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6
Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZ
mqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx
8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA
AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAV
YnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hp
anN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPE
xcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDx
2iiigAooooAKKKKACiiigAooooAKKKnms7q2hhmntpoopxuid4yokHqpPUfSgLkF
FFFABRRRQAUUUUAdF4IttLu/EsUWreUYSjGNJn2o8n8KsfQ1peLJbyC0ez1Pwjp+
myFwYLqzh8se43DIfI9653RYNJ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Z5lrqkl9YzW5ie6jtjG0ZbuEfOcEChRTlHnfTv6+ZF2ufkX4feVdR8KWSaR
c6jo2uw6pHaEC5QQNEyAnAIBJ3DPeuXr0XxH4ma50S7hh8cnURIAv2M6SIi6kjI3
7RjA5/CvOqzqJKXu/wBfma0nJx97+vwQUUUVBqFFFFABRRRQAUUUUAFFFFABRRRQ
AUUUUAFFFFABRRRQAUUUUAf/2Q==
User avatar
SKAN
Posts: 1427
Joined: 29 Sep 2013, 16:58

Re: SetClipboardHTML()

13 Feb 2021, 09:31

@valuex

The following works fine for me:
 

Code: Select all

#NoEnv
#Warn
#SingleInstance, Force

base64string := "
( Join
/9j/4AAQSkZJRgABAQEAkACQAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS
Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ
CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy
MjIyMjIyMjIyMjIyMjL/wAARCAAvAIYDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEA
AAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIh
MUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6
Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZ
mqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx
8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA
AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAV
YnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ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b63p1hoZZEDi
yhGxULH5yqscnr3zwKseMIJYdI0Iprx1XTzHItqTa+T5aqVUjnk/j6VzVhDbXF9D
FeXf2S3Y4efyzJsHrtHJrsdaXwvc+GdPsrfxR5k+mxTeWv8AZ8o89nbcBzwvpnmp
VnTl69/6/I1fuziv0/r8x3w91zUfOuNG+0f8S/7LPJ5OxfvbeucZ/WuV0LRp9e1N
bKGSOIbTJJLIcLGg6sfpXSeC38O6W39o3/iDyLmSCWFrX7FI2zcCAd4yDxzUegar
pXhHxZ5lrqkl9YzW5ie6jtjG0ZbuEfOcEChRTlHnfTv6+ZF2ufkX4feVdR8KWSaR
c6jo2uw6pHaEC5QQNEyAnAIBJ3DPeuXr0XxH4ma50S7hh8cnURIAv2M6SIi6kjI3
7RjA5/CvOqzqJKXu/wBfma0nJx97+vwQUUUVBqFFFFABRRRQAUUUUAFFFFABRRRQ
AUUUUAFFFFABRRRQAUUUUAf/2Q==
)"

html := "
( LTrim
  <img src=""data:image/jpeg;charset=utf-8;base64," . base64string . """>
  <p> description about the image</p>
)"

SetClipboardHTML( html )

Return to “Scripts and Functions”

Who is online

Users browsing this forum: alf2314, DK_2012, dostroll, Igorkru, parth1 and 21 guests