auto save script for windows (Shift + Win + S) hotkey

5,640

Solution 1

Solution

As I understood the desired solution is expected as a -

..script that automatically executes once a snip has been taken, and saves the snip automatically to a specific location.

I will expand on "Use Task Scheduler to run a Powershell batch script" idea. This idea is not new and I am surprised this is not answered yet in fullest. So here we go..

Step 1: Task Scheduler

This will launch a Powershell script when User is logged in.

  • Open Task Scheduler and hit "Create Task..."
  • On the General Tab set the task to be run whether the user is logged in or not and Do not store passwords - these make Powershell script start in hiding

general-tab

  • On the Triggers tab, create a Trigger to be An log on and select your User below

triggers-tab

  • On the Actions tab, create an Action Start a program with powershell to be our program with following Argument -
-Command "Get-Content -Path 'D:\Apps\Windows Powershell Scripts\ScreenSnip Manager\Activate.ps1' -Raw | Invoke-Expression"

In short, the argument instructs the Powershell to load the lines of our script as one line and then execute it, thus going around the usual Windows restrictions regarding launching standalone scripts.

Note: The path to the script must be valid and must contain the file hereby named "Activate.ps1".

add-action

This concludes the Task. Close the Scheduler and let's move on.

Step 2: Powershell script

Foreword: Windows does create 3 files after the Snip - Screenshot, its Thumbnail (always 364x180 on my FullHD setup) and a Json file. All files are dumped to the same system directory ScreenClip, which as of Win10 21H1 is located at C:\Users\Your-username\AppData\Local\Packages\MicrosoftWindows.Client.CBS_cw5n1h2txyewy\TempState\ScreenClip. Our job in the loop is rather simple -

  • monitor the folder for the new files appearing there
  • then get the right picture
  • rename/copy to desired userspace folder
  • optionally clear out the ScreenClip folder

Next, create a file "Activate.ps1" somewhere. In my example, I have it stored at D:\Apps\Windows Powershell Scripts\ScreenSnip Manager\Activate.ps1

Content of the script

$watcher = New-Object System.IO.FileSystemWatcher;

$watcher.Path = "$HOME\AppData\Local\Packages\MicrosoftWindows.Client.CBS_cw5n1h2txyewy\TempState\ScreenClip";

$watcher.Filter = "*.png";

$watcher.NotifyFilter = "FileName";

$watcher.EnableRaisingEvents = $true;

$action = {

    $path = $Event.SourceEventArgs.FullPath;

    # Last chance for a file to unlock;
    Start-Sleep -Milliseconds 100;
    
    try {

        Add-Type -AssemblyName System.Drawing;

        # Open image file;
        $png = [System.Drawing.Image]::FromFile((Get-Item $path));

        $dimensions = -join ($png.Width, " x ", $png.Height);

        # Skip automatic thumbnails which are always the same size;
        If ($dimensions -ne "364 x 180") {
             Copy-Item -Path $path -Destination "$HOME\Downloads\Screenshot-$(get-date -f yyyy-MM-dd-HHmmss.fff).png"; 
        }
        
    } catch {
        
        Write-Host "Problem acquiring image";

    } finally {
        
        $png.Dispose();
    }

}

Register-ObjectEvent -InputObject $watcher -EventName "Created" -SourceIdentifier 'SnipGrab' -Action $action;

Remove-Item -Path (Join-Path $watcher.Path '\*') -Recurse;

while ($true){  Wait-Event -SourceIdentifier "SnipGrab";  };

As the code suggests, Snips are copied to the Username\Downloads folder and get renamed to something like Screenshot-2021-05-17-213501.033.png. Make sure to tweak the desired path and resulting file names.

There is really nothing complicated in the script from the first look, but it had bumps. Images must be handled cautiosly and resources released in code. A freshly created original snip is often not available at the same moment - its content is still being written to disk thus I added 100 ms waiting time for the file write to complete. I am happy to finally compile the bits from here and there into the working variant. This is my literally second Powershell script and it took a night to read the docs and test things. Hope it helps)

Solution 2

[UPDATED Oct. 2020]:

According to the Reddit post found at https://www.reddit.com/r/Windows10/comments/aia21t/snip_sketch/elt5ajt/ it seems that windows already temporarily saves a file in one of its Windows ShellExperience Host folders which means you could simply have the script make a duplicate file to be saved in the directory of your choice as soon as a file is modified or updated in that other temporary holding directory (Of screen clips made)

This means that the entire previous post below is considered irrelevant now and has only been left up for general reference and does not offer/cover the more simple solution as discussed above

[END OF UPDATE]

TLDR - Honestly, you're going to have to install at least one third party software to accomplish this (i.e. AutoHotKey) unless you can figure out the Powershell step. Otherwise, I couldn't find any arguments to add that would work for the route I took, so if you're still adamant about not using ANY third party software, best of luck.


I was considering working on such a script for quite some time as I found myself often using the Screen Snip tool numerous times and the hassle of clicking and opening then hitting save and designating a name became quite a nuisance AND time consuming.

Although it's not a complete answer, it's was the best I could come up with before giving up to using a third party software (which was only maybe a 2MB install btw- Greenshot). If you're able to fill in the missing bits, please let me know.

Overview

  • Use Event Viewer to track whenever Screen Snip is used and act as the trigger
  • Use Task Scheduler to commit the action of saving expedite the action of saving by immediately opening paint
  • Use your uber micro skills to hit Ctrl+V then Ctrl+S type file name and hit enter (assuming you set the directory from the first time)

~OR~

  • Use Task Scheduler to run a Powershell batch script
  • Use Task Scheduler to run AutoHotKey script to automatically open paint, paste, and save the file for you (which involves third party software)

Step 1: Event Viewer

  • Run secpol.msc (AKA Local Security Policy)
  • On the left go to Local Policies then Audit Policy
  • Then Double Click "Audit process tracking" and mark the checkbox for "Success"

Step 2: Create scheduled task based on trigger

This will automatically open paint whenever the Screen Snip tool is used

  • Open Task Scheduler and hit "Create Task..." *(Making sure NOT to use Create basic task)
  • On the General Tab, name the task whatever you'd like
  • On the Triggers tab, click "New", and for the drop down menu selection "Begin the task:" select "On an event"
  • Select "Custom" then click "New Event Filter..."
  • At the top, select the "XML" tab and hit the checkbox for "Edit Query Manually" and enter the following if you want Paint to open immediately after you make your selection:
<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and Task = 13312 and (band(Keywords,9007199254740992)) and (EventID=4688)]] 
   and 
     *[EventData[Data[@Name='NewProcessName'] and (Data='C:\Windows\System32\backgroundTaskHost.exe')]] 
   and 
     *[EventData[Data[@Name='ProcessId'] and (Data='0x54c')]]
    </Select>
  </Query>
</QueryList>

WARNING The above option attempts to limit the process from being trigger by other applications using BackgroundTaskHost by specifying the Process ID (which you can obtain from Event Viewer) HOWEVER It is possible the Process ID can change and why this is basically impossible without assistance of a third party software in trying to use Screen Snip from Snip & Sketch have "automatic" save

The more exact option which prevents the event triggering from another application and is exact to Screen Snip but requires you click the notification that pops up after your Screen Snip in order to trigger is as follows:

<QueryList>
  <Query Id="0" Path="Security">
    <Select Path="Security">*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and Task = 13312 and (band(Keywords,9007199254740992)) and (EventID=4688)]] 
   and 
     *[EventData[Data[@Name='NewProcessName'] and (Data='C:\Program Files\WindowsApps\Microsoft.ScreenSketch_10.1907.2471.0_x64__8wekyb3d8bbwe\ScreenSketch.exe')]]
    </Select>
  </Query>
</QueryList>

This is because Screen Snip is constantly running in the background and when you create the screen snip, the process used is BackgroundTaskHost as a subprocess of RuntimeBroker and svchost. So in order to make the event trigger particular to screen snip (Snip & Sketch), you would need to click on the preview image notification that pops up in order to bring Snip & Sketch from background process to Active Task

Click OK and OK to return to the Task creation window.

Task Creation continued

  • Now go to the Actions tab
  • Select "New..."
  • The default "Action:" should be "Start a program" if not select it
  • Then browse to mspaint.exe (usually %windir%\system32\mspaint.exe)
  • hit OK and OK and you're done
  • Now you're all set to utilize your uber micro skills as mentioned in the Overview on the third bullet point

Alternative Actions for Task Scheduler

Below are some alternative actions I explored in attempting to accomplish this in writing this article:

  • Use a Powershell batch script For your benefit, this method doesn't require third party program if you can figure it out, I gave up after the amount of time I spent writing this article and hating myself for it
  • Using AutoHotKey

Ironically, before even figuring all this out, I had already given up and downloaded, installed, and utilized Greenshot yet my insatiable desire to finally provide an answer has left me publishing this 6 hours later.

Share:
5,640

Related videos on Youtube

Vasu Deo.S
Author by

Vasu Deo.S

Updated on September 18, 2022

Comments

  • Vasu Deo.S
    Vasu Deo.S over 1 year

    Windows has an inbuilt hotkey (Win + Shift + S) which executes snipping tool in rectangular strip mode, any screen captured will be copied to the clipboard as an image.

    I am currently working on finding the most efficient way, in which we can pair the inbuilt shortcut key, with some script that automatically executes once a snip has been taken, and saves the snip automatically to a specific location.

    I have already tried using Keyboard, pyautogui etc modules in Python for getting/creating keyboard events. The problem is that these modules are really slow and not consistent especially on slow hardware.

    I am looking forward to a solution that makes use of windows inbuilt shortcut, and works over it.

    Thanks in Advance.

    • Vasu Deo.S
      Vasu Deo.S about 5 years
      I don't want to install a new software/application
    • A__
      A__ almost 5 years
      Any solution to this?
    • Vasu Deo.S
      Vasu Deo.S almost 5 years
      @A__ Sadly No. But a good news is that now (on latest windows 10 build) once you take a screenshot via Win + Shift + S, you get a option of saving/customizing it as soon as it is taken. But that doesn't actually solve the problem in of Grabbing windows inbuilt shortcut and working over it. I achieved little success via using autohotkey, as it overrides the inbuilt shortcut but it also has its own share of problems.
  • Christian Mann
    Christian Mann over 3 years
    Apparently the screenshots also get dumped to a certain location in %APPDATA%, so perhaps it might be more productive to simply monitor that folder? answers.microsoft.com/en-us/windows/forum/all/…
  • Doedigo
    Doedigo over 3 years
    Wow, great find, thank you @ChristianMann!! This simplify things by A LOT. Apparently it's one or two possible directories but in my case, I found it to be "C:\Users\%USERNAME%\AppData\Local\Packages\Microsoft.Window‌​s.ShellExperienceHos‌​t_cw5n1h2txyewy\Temp‌​State\ScreenClip" So now, all you have to do is to have a script duplicate the file every time a new file is generated in the folder, and have it pasted to whatever folder is most convenient. By now, I've gotten used to my third party software but learning new ways to attack an old problem is definitely insightful, sincere thanks!
  • Vasu Deo.S
    Vasu Deo.S almost 3 years
    @Doedigo +1 Sorry for late reply. The answer is a good alternative to the accepted solution. Also could you guide me, to where I can find information/guide regarding Event Viewer, as I am not much literate in using it.
  • Vasu Deo.S
    Vasu Deo.S almost 3 years
    Nice answer +1. I think the problem basically boiled down to discovering the location of the temporary saved image files, and then creating a watchdog on that location for new images.
  • Doedigo
    Doedigo almost 3 years
    @VasuDeo.S Thank you. To clarify, Event Viewer is the title of the program used to view entries in the Windows Event Log, more information can be found at docs.microsoft.com/en-us/windows/win32/wes/… whereas windows 10 introduced TraceLogging and would be the equivalent I believe, of the event log and event viewer docs.microsoft.com/en-us/windows/win32/tracelogging/…
  • Cristy
    Cristy over 2 years
    Thanks for the script! It works fine, except that there are still two images created (a high-res one, and a smaller one, but the small one is not 364x180, the size varies). Any way to just save the native resolution image?
  • Cristy
    Cristy over 2 years
    Nevermind, the small size is always the same, but it's 546 x 270 in my case, which is 1.5x larger. I assume this is because of the screen DPI/scaling factor which is for 150% on my 4k screen.