Code: Select all
; Windows only
; tested with PB 5.73 (x64) on Windows 11
; https://www.purebasic.fr/english/viewtopic.php?t=79284
EnableExplicit
Global g_ClipboardHistoryFormat.i = RegisterClipboardFormat_("CanIncludeInClipboardHistory")
Global g_CloudClipboardFormat.i = RegisterClipboardFormat_("CanUploadToCloudClipboard")
Procedure.i SetClipboardTextPrivate (text$)
; -- Copy text to the clipboard in a way, so that it does not appear in the clipboard history or in the cloud clipboard of Windows 10+
; in : string to copy
; out: 0 on success,
; > 0 on error
;
; after
; - Charles Petzold:
; Programming Windows,
; 5th ed. 1998.
; Chapter 12: "The Clipboard"
; - https://stackoverflow.com/questions/53190273/bypass-clipboard-history-in-the-windows-10-october-2018-update
Protected *str, hZeros.i, hString.i, ret.i=0
If Asc(text$) =''
ProcedureReturn 0 ; success
EndIf
hZeros = GlobalAlloc_(#GHND|#GMEM_SHARE, 4)
If hZeros = #Null
ProcedureReturn 1
EndIf
hString = GlobalAlloc_(#GHND|#GMEM_SHARE, (lstrlen_(text$)+1) * SizeOf(Character))
If hString = #Null
GlobalFree_(hZeros)
ProcedureReturn 2
EndIf
*str = GlobalLock_(hString) ; translate the handle into a pointer
CopyMemoryString(@text$, @*str) ; copy the string into the global memory block
GlobalUnlock_(hString)
If OpenClipboard_(0) = #False
ret = 3
Else
EmptyClipboard_()
If SetClipboardData_(g_ClipboardHistoryFormat, hZeros) = #Null ; This hides the text from the clipboard history!
ret = 4
EndIf
If SetClipboardData_(g_CloudClipboardFormat, hZeros) = #Null ; This prevents upload of the text to the cloud clipboard!
ret = 5
EndIf
If SetClipboardData_(#CF_UNICODETEXT, hString) = #Null
ret = 6
EndIf
CloseClipboard_()
EndIf
If ret > 0
GlobalFree_(hZeros)
GlobalFree_(hString)
EndIf
ProcedureReturn ret
EndProcedure
CompilerIf #PB_Compiler_IsMainFile
Define c$
c$ = Str(Random(9999))
Select SetClipboardTextPrivate(c$)
Case 0
MessageRequester("OK", ~"Copied:\n" + c$)
Case 1
MessageRequester("Error", "Can't allocate 4 zero bytes in global memory.")
Case 2
MessageRequester("Error", "Can't allocate global memory for the string.")
Case 3
MessageRequester("Error", "Can't open the clipboard.")
Case 4
MessageRequester("Error", "Can't write data in ClipboardHistory format.")
Case 5
MessageRequester("Error", "Can't write data in CloudClipboard format.")
Case 6
MessageRequester("Error", "Can't put the string into the clipboard.")
EndSelect
CompilerEndIf