I want to create a visual interface for browsing clipboard images.
Therefore, I will have a process that listens for the contents of the clipboard.
My question is:
Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase
$previousImageHash = $null
while ($true) {
$image = [System.Windows.Clipboard]::GetImage()
if ($image) {
$currentImageHash = $image.GetHashCode()
if ($currentImageHash -ne $previousImageHash) {
Write-Host $currentImageHash
$previousImageHash = $currentImageHash
}
}
Start-Sleep -Seconds 1
}
After running the above code, when I copy an image to the clipboard, it will keep printing continuously.
What I don't understand is, if I'm not copying a new image to the clipboard, it should only print once.
Or is it that every time GetImage
is called, it not only retrieves the image information but also writes some additional information (like time) into the clipboard?
If I don't want to change the clipboard, is there any way to detect image changes?
try to use Clipboard Sequence Number
and see this answer
Add-Type -NameSpace WinApi -Name ClipboardSeq -MemberDefinition '[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();'
Add-Type -NameSpace WinApi -Name CountClipboardFmt -MemberDefinition '[DllImport("user32.dll")] public static extern int CountClipboardFormats();'
$lastSequenceNumber = [WinApi.ClipboardSeq]::GetClipboardSequenceNumber()
while($true) {
$newSequenceNumber = [WinApi.ClipboardSeq]::GetClipboardSequenceNumber()
if( $lastSequenceNumber -ne $newSequenceNumber ) {
$lastSequenceNumber = $newSequenceNumber
"Clipboard has changed. New sequence number is: $newSequenceNumber"
$numFormats = [WinApi.CountClipboardFmt]::CountClipboardFormats()
"Number of formats in clipboard: $numFormats"
}
Start-Sleep 1
}