Snipper - Window Snipping Tool

Post your working scripts, libraries and tools.
User avatar
FanaticGuru
Posts: 1945
Joined: 30 Sep 2013, 22:25

Re: Snipper - Window Snipping Tool

02 May 2023, 18:06

Added OCR extension to the Snipper Extensions post here:

Snipper Extensions

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
Krd
Posts: 405
Joined: 10 Mar 2020, 02:46

Re: Snipper - Window Snipping Tool

03 May 2023, 07:58

Wow, works great! Thank you for that Extension!

But, for me it does not do OCR before the size "tooltip?" is displayed. It means that e.g a single word "Hello" doesn't ocr. Why?
User avatar
FanaticGuru
Posts: 1945
Joined: 30 Sep 2013, 22:25

Re: Snipper - Window Snipping Tool

03 May 2023, 12:32

Krd wrote:
03 May 2023, 07:58
Wow, works great! Thank you for that Extension!

But, for me it does not do OCR before the size "tooltip?" is displayed. It means that e.g a single word "Hello" doesn't ocr. Why?
It appears the OCR library will not process images that are smaller than a certain size in either dimension. I am not sure why.

It just happens that minimum size is close to the size where I display the dimension text when snipping. But it is not exactly the same. I believe it is just a coincidence that the minimum size is close to when my script displays dimensions and not. I can get images that will not OCR even though my script displayed the dimensions. It appears the minimum image size for OCR is 40 pixels in either dimension. It is almost like it is hard coded in the OCR library. 40 works, 39 does not, even though my script will display dimensions slightly lower than 39.

It is not about the text size either. More white space around text of the same size will make it work.

Here is the thread for the OCR by @Descolada
viewtopic.php?f=83&p=518931

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
Descolada
Posts: 1431
Joined: 23 Dec 2021, 02:30

Re: Snipper - Window Snipping Tool

03 May 2023, 12:52

@FanaticGuru, it appears you've found an undocumented minimum size for Window.Media.Ocr engine. It's interesting that MaxImageDimension property is provided, but MinImageDimension is not. I'm a bit wary of adding it to the library though, because they might decide to change it later on (it being undocumented after all) :/ I'll add it as a comment though...
Krd
Posts: 405
Joined: 10 Mar 2020, 02:46

Re: Snipper - Window Snipping Tool

04 May 2023, 05:28

One word is being used so frequently here that I would greatly appreciate it if @Deskolada could also work on this.
You never know what the future may bring and if it doesn't take too much of your time, so I hope it's not too much to ask for. :)
User avatar
FanaticGuru
Posts: 1945
Joined: 30 Sep 2013, 22:25

Re: Snipper - Window Snipping Tool

05 May 2023, 15:33

Krd wrote:
04 May 2023, 05:28
One word is being used so frequently here that I would greatly appreciate it if @Deskolada could also work on this.
You never know what the future may bring and if it doesn't take too much of your time, so I hope it's not too much to ask for. :)

Updated the OCR extension with updated OCR library that seems to address the 40 pixel lower limit.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
Krd
Posts: 405
Joined: 10 Mar 2020, 02:46

Re: Snipper - Window Snipping Tool

06 May 2023, 13:06

Damn, just wow!

This is such a useful tool now. :=)

:bravo:
gbb
Posts: 3
Joined: 27 Apr 2018, 09:41

Re: Snipper - Window Snipping Tool

15 May 2023, 13:17

Changing Snipper to use extensions was a spectacular change!

To better organize files, I've stored extensions into a subdirectory of the main Snipper directory called "Lib" - by putting in an #Include Lib statement before the others, you can store extensions in that subdirectory without needing to change the basic syntax outlined in the main Snipper post, e.g. #Include Snipper - Extension - PDF.ahk.


Here's a modification of the Acrobat Extension. I wanted to have the option to Copy to Acrobat OR make the PDF silently. I played with some options to do it silently in Acrobat, but couldn't quite get it to work how I wanted. Instead, I used the img2PDF.exe file ahk7 shared. It would be easy to tweak it not to use Acrobat at all, albeit without the copy option.

Code: Select all

; Snipper - Extension - PDF
Extensions.Push({ PDF: { Text: 'COPY: Acrobat PDF', Func: Clipboard2PDF } })
Extensions.Push({ PDF: { Text: 'SAVE:  PDF', Func: Clipboard2PDF.Bind(,GetFullPathName('.\Snipper - PDF\')) } })
Clipboard2PDF(Borders := false, PDFSavePath := '')		; Adobe Acrobat must be installed
{
	If (PDFSavePath = "")
	{
		; Put Active Snip on Clipboard
		Snip2Clipboard(Borders)
		Try App := ComObject('AcroExch.App')
		Catch
			{
				MsgBox 'Could not Open Adobe Acrobat COM'
				return
			}
		App.Show()
		App.MenuItemExecute('ImageConversion:Clipboard')
	}

	else
	{
		If !FileExist(PDFSavePath)
			DirCreate(PDFSavePath)
		SavedImageFile:= Snip2File(,Settings_SavePath_Image)
		TimeStamp := FormatTime(, 'yyyy_MM_dd @ HH_mm_ss')
		FileName := TimeStamp '.PDF'
		FullPDFPath := PDFSavePath FileName
		Commands := A_ScriptDir "\lib\img2pdf.exe " "`"" SavedImageFile "`"" " -o " "`"" FullPDFPath "`""
		Run A_ComSpec " /c " Commands,,"Hide"
		
	}
}
Finally, while this last extension is pretty rudimentary, it'll open the Snipper Forum post so you can check for updates. I'm sure it could be updated to log when you last checked, or scrape the post looking for an update, but for now it's a step up from saving a bookmark in your browser.

Code: Select all

; CheckUpdate - Open Forum Post for Snipper to Manually look for updates

Extensions.Push({ SM: { Text: 'OPEN:  Check Snipper Forum Post for Update', Func: CheckUpdate } })

CheckUpdate(borders := false)
{
	try run "https://www.autohotkey.com/boards/viewtopic.php?f=83&t=115622"
}
gbb
Posts: 3
Joined: 27 Apr 2018, 09:41

Re: Snipper - Window Snipping Tool

15 May 2023, 13:59

I still can't edit posts yet, so I'll put this down instead: Per the Documentation, you can also store scripts to be used in include statements in the standard local library (a subdirectory of the main script directory called "Lib") if you use the syntax #Include <script to include>
Krd
Posts: 405
Joined: 10 Mar 2020, 02:46

Re: Snipper - Window Snipping Tool

19 May 2023, 05:07

FG, can you do it, or is it Deskolada that can do the following?

If I OCR multiple lines, they all become one single long line.

How can I OCR while keeping spaces and tabs as in the original source?

If you OCR the above lines, it would be as follows:
FG, can you do it, or is it Deskolada that can do the following? If I OCR multiple lines, they all become one single long line. How can I OCR while keeping spaces and tabs as in the original source?
Descolada
Posts: 1431
Joined: 23 Dec 2021, 02:30

Re: Snipper - Window Snipping Tool

19 May 2023, 08:31

@Krd, you can modify the method to loop over the lines and separate them with a new-line character. Untested:

Code: Select all

OCR2Clipboard(Borders := false)
{
	; Get Hwnd of Active Snip
	Hwnd := WinGetID('A')
	; Get hBitMap of Snip
	hBitMap := SendMessage(0x173, 0, 0, guiSnips[Hwnd].GuiObj.Pic)
	; OCR of hBitMap
	Result := OCR.FromBitmap(hBitMap)
	Text := ""
	for Line in Result.Lines
		Text .= Line.Text "`n"
	; Put Text in Clipboard
	A_Clipboard := Trim(Text)
}
wilkster
Posts: 19
Joined: 15 Jul 2020, 09:43

Re: Snipper - Window Snipping Tool

19 May 2023, 10:51

One thing that may be helpful is to add a cross mouse cursor while you are dragging.

Insert the SelectOn(true) just after the SelectScreenRegion call,
and Insert the SelectOn(false) after the loop grabbing the mouse is complete

Code: Select all

   Loop {
      MouseGetPos(&eX, &eY)
      W := Abs(sX - eX), H := Abs(sY - eY)
      X := Min(sX, eX), Y := Min(sY, eY)
      If A_Index < 50
         guiSSR.Background.Redraw()
      guiSSR.Move(X, Y, W, H)
      Display_WH(false)
      Sleep 10
   } Until !GetKeyState(Key, 'p')


   SelectOn(false) ; Restore Cursor TFW
Cursor code below

Code: Select all

SelectOn(On) {
   Static CROSS := 32515
   if (On)
      SetSystemCursor(CROSS)
   else
      SetSystemCursor()
}
;----------------------------------------------------------------------------
; Set the system cursor for resizing and moving
; https://www.autohotkey.com/boards/viewtopic.php?t=13284
;----------------------------------------------------------------------------
SetSystemCursor(Cursor := "") {
   Static Cursors := [32650, 32512, 32515, 32649, 32651, 32513, 32648, 32646, 32643, 32645, 32642, 32644, 32516, 32514]
   Static SPI_SETCURSORS := 0x57
   Static LR_SHARED := 0x8000
   Static U := "Uint"
   Static I := "Int"
   Static P := "Ptr"
   ; The line of code below loads a cursor from the system set
   If (Cursor == "") {
      ; Restore system cursor
      DllCall("User32.dll\SystemParametersInfoW", U, SPI_SETCURSORS, U, 0, P, 0, U, 0)
   } Else {
      ; LoadCursor is superseded, use LoadImage instead
      ; When loading a system icon or cursor, you must use LR_SHARED (0x8000) or the function will fail to load the resource
      hCursor := DllCall("User32.dll\LoadImage", U, 0, U, Cursor, U, 2, U, 0, U, 0, U, LR_SHARED)
      ; And than we set all the default system cursors to be our choosen cursor.
      ; CopyImage is necessary as SetSystemCursor destroys the cursor we pass to it after using it.
      For v in Cursors {
         DllCall("User32.dll\SetSystemCursor", U,
            DllCall("User32.dll\CopyImage", U, hCursor, U, 2, I, 0, I, 0, U, 0),
            U, v)
      }
   }
}
Krd
Posts: 405
Joined: 10 Mar 2020, 02:46

Re: Snipper - Window Snipping Tool

19 May 2023, 11:14

Thanks, it works for keeping the lines but not the empty space/line between the lines.
anhnha
Posts: 118
Joined: 08 Aug 2018, 02:46

Re: Snipper - Window Snipping Tool

24 May 2023, 04:43

I uninstalled v1, installed v2, and then launched the snipping tool. However, I was disappointed to find that it does not display the rectangular region while I'm dragging it. As a result, I am unable to determine its size or confirm if it is the desired region until I complete the dragging process. Is this the intended behavior, or have I made a mistake?
User avatar
FanaticGuru
Posts: 1945
Joined: 30 Sep 2013, 22:25

Re: Snipper - Window Snipping Tool

25 May 2023, 14:32

anhnha wrote:
24 May 2023, 04:43
I uninstalled v1, installed v2, and then launched the snipping tool. However, I was disappointed to find that it does not display the rectangular region while I'm dragging it. As a result, I am unable to determine its size or confirm if it is the desired region until I complete the dragging process. Is this the intended behavior, or have I made a mistake?

That is not expected behavior. There should be a semi-transparent green rectangle as you are dragging to select an area.

I am not sure what might be causing that issue. I would suggest some basic troubleshooting like reboot your computer and run just this script. See if that resolves the issue and then go from there.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks
Adollo
Posts: 1
Joined: 27 May 2023, 12:37

Re: Snipper - Window Snipping Tool

27 May 2023, 13:46

Hi! Sorry for my English! This is my first post here! This is my first extension! I'm really sorry! :-)

CopyCut for Explorer

Usage:
Use the context menu item to copy or cut the image as a file object for further insertion into the desired folder through the Explorer.

Code: Select all

/* ;--------------------------------------------------------------------------------------------------------------------
[Extension] CopyCut for Explorer (by Adollo)
File Name : Snipper - Extension - CopyCutForExplorer.ahk
Version : 2023 05 27

USAGE: Use the context menu item to copy or cut the image as a file object for further insertion into the desired folder through the explorer.

*/ ;---------------------------------------------------------------------------------------------------------------------

; CONTEXT MENU -------------------------------------------------------
Extensions.Push({ Explorer: { Text: 'COPY: Explorer File Object', Func: Explorer_Copy.Bind(,Settings_SavePath_Image, Settings_SavePath_Image_Ext) } })
Extensions.Push({ Explorer: { Text: 'CUT: Explorer File Object', Func: Explorer_Cut.Bind(,Settings_SavePath_Image, Settings_SavePath_Image_Ext) } })

;----- FUNCTIONS ------------------------------------------
Explorer_Copy(Borders := false, SavePath:='', FileExt:=''){
	FileName := Snip2File(Borders, Settings_SavePath_Image,, Settings_SavePath_Image_Ext)
	Explorer_ClipboardSetFiles FileName, "Copy"
}

Explorer_Cut(Borders := false, SavePath:='', FileExt:=''){
	FileName := Snip2File(Borders, Settings_SavePath_Image,, Settings_SavePath_Image_Ext)
	Explorer_ClipboardSetFiles FileName, "Move"
}

; Function Explorer_ClipboardSetFiles based on:
; Hey @just me, I got a similar problem where the application won't recognize the clipboard files with only CF_HDROP. 
; I fixed it by putting CF_FILENAME in addition. Please revise this cuz I don't know anything about C++ :D . 
; Also hope you can release your function in the Script and Libraries section, it's really useful.
; https://www.autohotkey.com/boards/viewtopic.php?p=63914#p63914
; Translation function to AHK version 2 by Adollo

Explorer_ClipboardSetFiles(FilesToSet, DropEffect := "Copy") {
   ; FilesToSet - list of fully qualified file pathes separated by "`n" or "`r`n"
   ; DropEffect - preferred drop effect, either "Copy", "Move" or "" (empty string)
   Static A_IsUnicode := 1
   Static TCS := A_IsUnicode ? 2 : 1 ; size of a TCHAR
   Static PreferredDropEffect := DllCall("RegisterClipboardFormat", "Str", "Preferred DropEffect")
   Static DropEffects := Map(1, 1, 2, 2, "Copy", 1, "Move", 2)
   ; -------------------------------------------------------------------------------------------------------------------
   ; Count files and total string length
   TotalLength := 0
   FileArray := []
   Loop Parse, FilesToSet, "`n", "`r"
   {
      If (Length := StrLen(A_LoopField))
         FileArray.Push({Path: A_LoopField, Len: Length + 1})
      TotalLength += Length
   }
   FileCount := FileArray.Length
   If !(FileCount && TotalLength)
      Return False
   ; -------------------------------------------------------------------------------------------------------------------
   ; Add files to the clipboard
   If DllCall("OpenClipboard", "Ptr", A_ScriptHwnd) && DllCall("EmptyClipboard") {
      ; HDROP format ---------------------------------------------------------------------------------------------------
      ; 0x42 = GMEM_MOVEABLE (0x02) | GMEM_ZEROINIT (0x40)
      hDrop := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", 20 + (TotalLength + FileCount + 1) * TCS, "UPtr")
      pDrop := DllCall("GlobalLock", "Ptr", hDrop)
      Offset := 20
      NumPut("UInt", Offset, pDrop + 0)         ; DROPFILES.pFiles = offset of file list
      NumPut("UInt", !!A_IsUnicode, pDrop + 16) ; DROPFILES.fWide = 0 --> ANSI, fWide = 1 --> Unicode
      For Each, File In FileArray
         Offset += StrPut(File.Path, pDrop + Offset, File.Len) * TCS
      DllCall("GlobalUnlock", "Ptr", hDrop)
      DllCall("SetClipboardData", "UInt", 0x0F, "UPtr", hDrop) ; 0x0F = CF_HDROP
      
      File := FileArray[1]

      VarSetStrCapacity(&ShortPath, 260) ; V1toV2: if 'ShortPath' is NOT a UTF-16 string, use 'ShortPath := Buffer(260)'
      ShortLength := DllCall("GetShortPathName", "Str", File.Path, "Str", ShortPath, "Uint", 260)
      hName := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", ShortLength + 1, "UPtr")
      pName := DllCall("GlobalLock", "Ptr", hName)
      StrPut(ShortPath, pName, ShortLength, "CP0")
      DllCall("GlobalUnlock", "Ptr", hName)
      DllCall("SetClipboardData", "UInt", 0xC006, "Ptr", hName) ; 0xC006 = CF_FILENAME

      hNameW := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", File.Len * TCS, "UPtr")
      pNameW := DllCall("GlobalLock", "Ptr", hNameW)
      StrPut(File.Path, pNameW, File.Len * TCS)
      DllCall("GlobalUnlock", "Ptr", hNameW)
      DllCall("SetClipboardData", "UInt", 0xC007, "Ptr", hNameW) ; 0xC007 = CF_FILENAMEW

      ; Preferred DropEffect format ------------------------------------------------------------------------------------      
	  If (DropEffect := DropEffects[DropEffect]) {
         ; Write Preferred DropEffect structure to clipboard to switch between copy/cut operations
         ; 0x42 = GMEM_MOVEABLE (0x02) | GMEM_ZEROINIT (0x40)
         hMem := DllCall("GlobalAlloc", "UInt", 0x42, "UInt", 4, "UPtr")
         pMem := DllCall("GlobalLock", "Ptr", hMem)
         NumPut("UChar", DropEffect, pMem + 0)
         DllCall("GlobalUnlock", "Ptr", hMem)
         DllCall("SetClipboardData", "UInt", PreferredDropEffect, "Ptr", hMem)
      }
      DllCall("CloseClipboard")
      Return True
   }
   Return False
}

This file can be added to Snipper by including it in the same directory as the Snipper script, and then adding or uncommenting the appropriate #include line in the #INCLUDE EXTENSION section of the Snipper script.
#Include Snipper - Extension - CopyCutForExplorer.ahk
anhnha
Posts: 118
Joined: 08 Aug 2018, 02:46

Re: Snipper - Window Snipping Tool

28 Jun 2023, 02:33

FanaticGuru wrote:
25 May 2023, 14:32
anhnha wrote:
24 May 2023, 04:43
I uninstalled v1, installed v2, and then launched the snipping tool. However, I was disappointed to find that it does not display the rectangular region while I'm dragging it. As a result, I am unable to determine its size or confirm if it is the desired region until I complete the dragging process. Is this the intended behavior, or have I made a mistake?

That is not expected behavior. There should be a semi-transparent green rectangle as you are dragging to select an area.

I am not sure what might be causing that issue. I would suggest some basic troubleshooting like reboot your computer and run just this script. See if that resolves the issue and then go from there.

FG
Apologies for the delay in my response.
It appears that there might have been an issue with the installation process. I tried to reinstall it, and now it is functioning properly.
However, there is one extension that seems to be missing. In the previous version, v1, Juho implemented a feature whereby double-clicking on a clipped window would reduce its size to a very small region. Another double-click would then restore the window to its original size.
I'm wondering if there are any skilled users who could potentially add this functionality.
Here is the link to the feature (and the full code on his website):
https://youtu.be/kCmaH9fX3ZA?t=334
User avatar
JoeSchmoe
Posts: 129
Joined: 08 Dec 2014, 08:58

Re: Snipper - Window Snipping Tool

24 Jul 2023, 15:13

Hi @FanaticGuru, thanks for this script - I find myself using it quite frequently and I really miss it when I don't have it.

Have you considered putting it up on github? Many of the best scripts are distributed that way, and people might add code improvements via pushes. Also, it would allow you to put all of the extensions in a subdirectory (perhaps including user contributed extensions), so everything could be downloaded at once.

If I could make a feature request, I have one script that is always running, and I 'd love to be able to #include this script within it. However, when I do so, I get an error, so I presume it's not currently designed for that.

Either way, great script!
User avatar
MrDodel
Posts: 102
Joined: 28 Apr 2021, 09:03
Location: Event Horizon

Re: Snipper - Window Snipping Tool

24 Jul 2023, 16:28

JoeSchmoe wrote:
24 Jul 2023, 15:13
If I could make a feature request, I have one script that is always running, and I'd love to be able to #include this script within it. However, when I do so, I get an error, so I presume it's not currently designed for that.
If you can offer the error code it can help debug, rather than guess.
So much universe, and so little time. GNU Sir Terry.
User avatar
JoeSchmoe
Posts: 129
Joined: 08 Dec 2014, 08:58

Re: Snipper - Window Snipping Tool

24 Jul 2023, 21:28

Thanks. Here you go:
Error: Target window not found.

Specifically: ahk_id329502

---- C:\Myscript\Snipper\Snipper.ahk
522: OnMessage(0x6, WM_ACTIVATE)
524: {
▶ 526: If WinGetTitle('ahk_id' hwnd) = 'SnipperWindow'
527: If (Activated := wParam << 48 >> 48)
528: SnipWinBorderColor(guiSnips[hwnd].GuiObj, 'Green')

Call stack:
C:\Myscript\Snipper\Snipper.ahk (526) : [WinGetTitle] If WinGetTitle('ahk_id' hwnd) = 'SnipperWindow'
C:\Myscript\Snipper\Snipper.ahk (526) : [WM_ACTIVATE] If WinGetTitle('ahk_id' hwnd) = 'SnipperWindow'
> OnMessage
C:\Myscript\Snipper\Snipper.ahk (298) : [Gui.Prototype.Show] guiSSR.Show('x' sX ' y' sY ' w1 h1')
C:\Myscript\Snipper\Snipper.ahk (298) : [SelectScreenRegion] guiSSR.Show('x' sX ' y' sY ' w1 h1')
C:\Myscript\Snipper\Snipper.ahk (145) : [<Hotkey>] Area := SelectScreenRegion('LButton')
> #Lbutton

Return to “Scripts and Functions (v2)”

Who is online

Users browsing this forum: No registered users and 38 guests