PixPin
Settings

Scripts

Create PixPin scripts for screenshots, pins, and automation. Learn JavaScript syntax, API parameters, constants, platform differences, and troubleshooting.

PixPin scripts use JavaScript to call screenshot, pin, and window operations. Save repeated steps as an action, then trigger it with a shortcut, tray menu, or command line. Scripts is a manual chapter; the app's editor is under Configuration → Shortcuts/Actions.

  • Capture the active windowCapture and copy in one action.
  • Fixed capture areaReuse the same position and size.
  • Open a set of referencesPass a file list to create pins in a batch.
Save repeated operations as a script, then bind it to a shortcut or tray menu entry. All scene contents are fictional.

When to use scripts

NeedHow a script helps
Always capture the same areaFix the position and size, or generate a specified-size area around the pointer
Use the toolbar lessCopy, pin, save, or recognize immediately after selection
Avoid manual selection each timeDirectly capture the active window, the screen under the pointer, or the last capture region
Open a set of reference files every dayCreate several pins at once from an array of file paths
Connect operations to other toolsRun script text or a .js file from the command line

To change a shortcut, adjust a tray entry, or exclude a program, use Shortcuts/actions settings directly. Scripts suit combined operations and specific parameters.

Create and run your first script

A preset fills in the name and script; lines stand in for the script here. Enable the tray entry and apply, then set a shortcut in the action list.

Open Configuration → Shortcuts/Actions and click Add New Action. Start with a suitable Preset, such as Screenshot and... → Screenshot and pin.

Give the action a unique name, then review or edit the Script field. The following line starts capture and pins the result once you confirm the selection.

pixpin.screenShot(ShotAction.Pin);

Click Test Script, complete a real screenshot, and check the result. Errors appear if the test fails.

Click Apply, then assign a shortcut in the list. You can also check Tray menu and run the action from that entry later.

Testing really executes the script. Selecting another preset overwrites the editor, and canceling the window does not undo operations already tested. Built-in action scripts cannot be edited; create a custom action for a variation.

Run from the command line

Put script text after -r, or a script file path after -f. If PixPin is running, it passes the request to the existing instance; on first launch, execution waits for initialization.

Windows PowerShell: Replace the executable path with your installation location:

& 'D:/Apps/PixPin/PixPin.exe' -r 'pixpin.screenShot(ShotAction.Copy);'
& 'D:/Apps/PixPin/PixPin.exe' -f 'D:/Scripts/capture.js'

macOS Terminal: These examples assume the app is installed in Applications:

"/Applications/PixPin.app/Contents/MacOS/PixPin" -r 'pixpin.screenShot(ShotAction.Copy);'
"/Applications/PixPin.app/Contents/MacOS/PixPin" -f '/Users/yourname/Scripts/capture.js'

Write only JavaScript in the file, without code-fence markers. For Chinese text, saving as UTF-8 with a BOM is recommended. Prefer -f for long scripts to reduce terminal quoting, backslash, and $ escaping issues. Keep surrounding quotes when paths contain spaces.

A command-line return does not mean capture, recognition, or saving has finished. This entry point does not return the last script expression as structured data either. Automated calls on macOS do not proactively show permission guidance for interactive capture; grant screen recording and accessibility permissions inside the app first.

Supported syntax and execution

The script field accepts JavaScript. API and constant names are case-sensitive: use pixpin.screenShot, not pixpin.screenshot.

CategoryCommon supported forms
Variables and datavar, let, const; numbers, strings, booleans, arrays, objects, and null
Conditions and loopsif / else, switch, for, while, for...of, and break
Functions and classesfunction, arrow functions, parameters, return, and class; return cannot appear directly outside a function
Common expressionsArithmetic and comparison, &&, ||, !, ternary expressions, template strings, destructuring, and ??
Data processingBuilt-in objects such as Array, String, Math, Date, JSON, Map, and Set
Exceptionstry / catch / finally and throw new Error(...)

The current script environment does not support optional chaining ?. or async/await, and ordinary scripts cannot use import / export. Use if for null checks and PixPin APIs for operations with multiple stages.

There are no browser window, document, or fetch objects, no Node.js require, process, or fs, and no setTimeout. Do not paste examples that depend on web pages, Node.js, or third-party packages. Object support also does not mean an ordinary object can replace a rectangle required by an API.

Sequential execution does not wait for manual input

JavaScript statements execute in order, but a call that opens capture only starts the operation; it does not wait for your selection. For capture followed by pinning, use pixpin.screenShot(ShotAction.Pin) directly. Do not simply put capture and pin-from-clipboard calls on consecutive lines.

  • Act after selectionscreenShot: select an area, then copy or pin.
  • Known area, immediate capturedirectScreenShot: use a known area without manual selection.
Both methods can copy an image, but at different times. The dashed outline only marks the scripted area; it does not appear during execution.

The script engine is reused. Keep temporary variables inside functions where possible to avoid interference across runs. The multiline examples here use immediately invoked functions:

(function () {
  var width = 640;
  var height = 480;
  var rect = pixpin.genRectUnderCursor(width, height);
  pixpin.directScreenShot(rect, ShotAction.Copy);
})();

The final () invokes the function immediately. Do not wait for capture with an infinite loop; it blocks the UI execution thread. console.log(...) can write logs, but the editor has no interactive console.

Global objects, parameters, and return values

Name:Purpose
pixpinCall screenshot, pin, delay, window, and system-command APIs
ShotActionSpecify what happens after capture, such as ShotAction.Copy
PixConstSpecify special regions, such as PixConst.SpRectActiveWindow

Enter ordinary numbers, booleans, and strings directly; use a string array for file lists. Absolute file paths are recommended. JavaScript paths can use D:/Images/example.png, or escape backslashes as D:\\Images\\example.png.

Generate rectangles with these three APIs and pass the results unchanged to subsequent APIs:

CallMeaning
pixpin.genRect(x, y, width, height)Specify a screen position and size
pixpin.genRectUnderCursor(width, height)Generate a region centered on the pointer and adjust its position to fit the screen
pixpin.getSpRect(type)Read a special region; use a PixConst constant for type

Positions and sizes use logical screen coordinates; width and height should be positive. Coordinates can be negative with multiple displays. If space near the pointer is insufficient, genRectUnderCursor proportionally reduces the region to fit. Display scaling and save settings also affect the exported pixel dimensions. Do not pass {x: 100, y: 100, width: 640, height: 480} to a rectangle API; those fields do not generate a capture region.

A true return usually means the request was accepted, not that the user finished interacting. See the API tables for specific return semantics. APIs with no return value cannot determine whether saving succeeded.

Examples you can adapt

Capture and copy the active window

Bring the target app to the foreground, then trigger this action with a global shortcut. It captures immediately without manual selection.

pixpin.directScreenShotSpRect(
  PixConst.SpRectActiveWindow,
  ShotAction.Copy
);

When you click Test Script in the editor, the settings window may be the active window. Apply the action, then trigger it from the target app to assess the result.

Set an initial selection, then adjust it manually

Start ordinary capture, then set the selection to screen coordinates (100, 100) with size 640 × 480. You can still annotate or adjust it with the toolbar.

(function () {
  if (pixpin.screenShotAndEdit()) {
    pixpin.setScreenShotRect(100, 100, 640, 480);
    pixpin.setScreenShotRectRadius(4 / 3);
  }
})();

The name setScreenShotRectRadius can be misleading: it sets the aspect ratio, not a corner radius. Remove the last line if you do not need a fixed ratio.

Capture directly and save with a timestamp

This example directly captures the screen under the pointer. Replace the path with your save folder before running it; on macOS, use a path such as /Users/yourname/Pictures/....

(function () {
  var rect = pixpin.getSpRect(PixConst.SpRectScreenUnderMouse);
  pixpin.directScreenShotAndSaveTo(
    rect,
    "D:/Captures/PixPin_$yyyy-MM-dd_HH-mm-ss$.png"
  );
})();

The save feature expands time placeholders; see Path and filename variables. This API automatically adds numeric suffixes for duplicate filenames and shows no save notification. It returns neither a saved path nor a success flag.

Pin multiple reference files at once

Replace the paths in the array with existing files. Add more entries in the same format as needed.

(function () {
  var files = [
    "D:/Reference/layout.png",
    "D:/Reference/colors.png"
  ];
  if (!pixpin.pinFromFiles(files)) {
    throw new Error("没有找到可贴出的文件,请检查路径。");
  }
})();

Nonexistent files are skipped; an empty array or no existing paths returns false. true means existing files were handed to the pin feature, not that every format can display as an image.

Wait three seconds, then start capture

This is the simplest version with a cancelable countdown:

pixpin.delayScreenShotWithTips(3);

Use the following API to specify position and size. From left to right: seconds, whether position is specified, x, y, whether size is specified, width, height, reserved parameter, and aspect ratio.

pixpin.delayScreenShot(3, true, 100, 100, true, 640, 480, 0, 4 / 3);

Toggle a state with the same action

The following inverts the current disabled state: pause other global shortcuts when enabled, then press again to restore them.

pixpin.disableShortcuts(!pixpin.isDisableShortcuts());

This action's shortcut can undo this explicit disabled state. It is still subject to ignore lists and full-screen game status on Windows.

Custom API reference

These user-operation APIs are available to ordinary action scripts. rect must come from a rectangle-generation API, and action uses ShotAction. Brackets indicate optional parameters; do not type the brackets in actual code.

Screenshots and regions

APIParameters and purpose
screenShot(action)Start selection and execute action when confirmed. Returns a boolean; it can return false if capture is already open, long capture is in use, or permissions are insufficient
screenShotAndEdit()Equivalent to screenShot(ShotAction.Edit); show the screenshot toolbar after selection
screenShotAndCopy()Equivalent to screenShot(ShotAction.Copy)
screenShotAndPin()Equivalent to screenShot(ShotAction.Pin)
screenShotAndCopyOcr()Equivalent to screenShot(ShotAction.CopyOcrText); recognize and copy text
openCustomScreenShot()Open the custom/delayed screenshot window for manual parameter setup
setScreenShotRect(x, y, width, height)Set the selection in an existing capture window; call after successful screenShotAndEdit(). Returns false without a capture window
setScreenShotRectRadius(ratio)Set the rectangular selection's aspect ratio, such as 16 / 9, not rounded corners. Path selections do not use this ratio
switchScreenshotMode()Switch to the next screenshot mode while the capture window is visible; return false if no capture window is available
directScreenShot(rect, action)Capture a known region directly and run an action, without a return value. Suitable for copy, pin, save, and similar outputs
directScreenShotSpRect(type, action)Directly capture a PixConst region, equivalent to getSpRect(type) followed by direct capture
directScreenShotAndSaveTo(rect, filePath)Capture directly to a full file path; support save variables and add numeric suffixes for duplicate names. No return value

The table omits the repeated pixpin. prefix; actual calls use names such as pixpin.screenShotAndCopy(). Passing Edit, ImageEdit, LongShot, or GifShot to direct capture does not open the corresponding editor or recording window. Use screenShot(action) or a dedicated API below for those workflows.

Delays, long screenshots, and screen recording

APIParameters and purpose
delayScreenShot(seconds, hasPos, x, y, hasSize, width, height, radius, ratio)Open capture editing after a delay, with a minimum of 0.2 seconds. A new call replaces a pending delay of this type; true means the timer was set
delayScreenShotWithTips(seconds[, rect])Show a cancelable countdown, rounded to integer seconds with a minimum of 1. Pass a region or omit it to select manually afterward. No return value
longScreenShot(rect)Open a long screenshot window for the region; adjust its region if one already exists
openLongScreenShot(x, y, width, height)Specify the long screenshot region with four numbers instead of generating a rectangle first
gifScreenShot(rect)Open a recording window for the region, or adjust an existing one. The name retains GIF, but the recording UI determines the final format
openGifScreenShot(x, y, width, height)Specify the recording region with four numbers
gifShotPause()Toggle pause/resume; return false without a recording window
hasLongShotWidget()Return whether a long screenshot window exists

delayScreenShot uses the specified rectangle when both hasPos and hasSize are true. With only hasSize set to true, it generates the specified size around the pointer. Without a specified size, selection remains manual. radius is currently unused; pass 0. A positive ratio sets the aspect ratio; use -1 if it is not needed.

These APIs open or control windows; they do not mean automatic scrolling has finished or a video has been exported. Continue long capture and recording in their respective UIs.

Pins and batch management

APIParameters and purpose
pinFromClipBoard()Create a pin from the clipboard; during a screenshot or long screenshot, try to pin the current result. The return value cannot determine clipboard-pin success
pinFromFiles(files)files is an array of file paths; process existing files. Return false for an empty array or no existing files
pinSelectedFile()Pin the files selected in the file manager; return false if nothing is selected or reading fails. macOS involves automation permission
restoreLastClosedPin()Recover a pin under the existing recovery rules and return whether it succeeded
closeAllPin()Close current pin windows through the normal closing workflow
hideOrShowAllPin() / isAllPinHide()Toggle visibility of all pins / query whether all pins are hidden
hideOrShowPinsExceptSelected()Hide pins except the selection; call again to restore. Try the active pin if none is selected; if still none, prompt for a selection
switchPinGroup()Trigger a pin group switch
trigMousePenetration()Toggle click-through for the pin under the pointer; turn it off for all pins if the pointer is not over one
setAllPinToRoiMode() / unsetAllPinToRoiMode()Switch pins to thumbnail display / restore normal display; ROI here does not create a window pin
saveAllPinImageTo(folder)Batch-save exportable pin images to the folder, with numbered filenames and suffixes for duplicates. The argument is a folder, not a full filename
saveAllPinImageWithDialog()Show a folder picker before batch saving
destoryAllPin()Destroy all pins under current confirmation settings; ordinary close recovery cannot restore them. The API really is spelled destory; do not change it to destroy

System commands and other operations

APIParameters and purpose
translateClipboard()Send clipboard content to translation and return whether it started
disableShortcuts(disabled) / isDisableShortcuts()true pauses and false restores other global shortcuts / query this explicit disabled state. The query does not represent ignore lists or game status
moveCursorBy(dx, dy)Move the pointer by an offset for fine adjustments; rapid repeated calls accelerate, so total movement is not guaranteed to equal the sum of offsets
toggleWindowTopmostUnderMouse()Toggle keep-on-top for the window under the pointer. Windows can affect other apps; macOS only operates on PixPin's own windows
openConfigurationWindow() / openDoc()Open settings / the manual
runSystem(command)Start an external program and return immediately, without a return value; the string includes the executable and arguments
runSystemSync(command)Start an external program and wait synchronously; the returned object contains code, output, and error: exit code, standard output, and standard error
quit()Quit PixPin

runSystem and runSystemSync launch programs directly without automatically using a terminal interpreter. Pipes, redirection, and shell built-ins do not work automatically; explicitly specify the platform's interpreter when needed. The command string cannot be empty.

To open a calculator, Windows can use pixpin.runSystem("calc"); macOS can use pixpin.runSystem("/usr/bin/open -a Calculator"). The example below reads a synchronous command result; substitute a program available on your system:

(function () {
  var result = pixpin.runSystemSync("cmd /c ver"); // Windows 示例
  console.log(result.code, result.output, result.error);
})();

Synchronous waiting temporarily blocks the PixPin UI. The current implementation has a default wait limit of about 30 seconds, returns no separate timeout field, and code alone cannot prove the process started correctly. Use runSystem to return immediately.

Region and action constants

PixConst: where to capture

ConstantRegion
PixConst.SpRectScreenUnderMouseThe monitor under the pointer
PixConst.SpRectAllScreenThe rectangular extent of all screens
PixConst.SpRectWindowUnderMouseThe window under the pointer
PixConst.SpRectActiveWindowThe current active window
PixConst.SpRectLastShotRectThe last capture selection; complete a valid screenshot before using it

Regions depend on the windows, pointer, and history at execution time. Without a valid window or history, do not assume the returned region is usable.

ShotAction: what to do after selection

Prefix these names with ShotAction., for example ShotAction.QuickSave.

ConstantAction
EditContinue annotating and operating with the screenshot toolbar
Copy / PinCopy the image / pin it
Save / QuickSaveOpen the save window / use quick save settings
CopyOcrTextRecognize and copy text
TranslateTranslate screenshot content
OcrTable / OcrDocumentTable recognition / document recognition
LatexRecognitionFormula Recognition
LongShot / GifShotEnter long screenshot / screen recording
WinRoiCreate a window pin; Windows only
PrintPrint
CopyQRCodeTextRecognize and copy QR code content
AirDropAirDrop; macOS only
ImageEditOpen a separate image editor
CloseClose this capture

Constants select existing features without changing their operating conditions. Copying, saving, and recognition may still depend on settings or interactive windows.

Troubleshooting

SymptomWhat to check
SyntaxErrorCheck quotes, brackets, and commas; remove Markdown fence markers. Make sure you are not using ?., async/await, or import
ReferenceErrorCheck variable declarations, name capitalization, and scope
Method not found or call has no effectCheck capitalization and API spelling; generate rectangles with dedicated APIs and use arrays for file lists
The settings window was capturedSettings was in the foreground during Test Script; apply the action, switch to the target app, and use the shortcut
Capture started but there is no final imagescreenShot(...) still needs a manual selection; use directScreenShot... for direct capture
No save notificationdirectScreenShotAndSaveTo does not show one; check the path, extension, and output folder
The shortcut did not trigger the scriptCheck registration status, the disable setting, and ignore lists; see Shortcut status
macOS command-line capture did not respondConfirm screen recording and accessibility permissions in PixPin first, and make sure the system is unlocked

Use try / catch to catch script errors, but returning false or having no return value does not automatically throw an exception. Debug one operation first, then add parameters and combinations gradually. No error does not prove every result has finished.

On this page