win

package
v1.3.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 1, 2026 License: Apache-2.0 Imports: 19 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for windows/amd64

Overview

Package win provides a pure-Go Windows implementation of the robotgo API for desktop automation: mouse, keyboard, screen capture, window management and process enumeration.

Unlike the upstream go-vgo/robotgo, this package uses NO Cgo. It is built entirely on top of the Win32 API bindings in github.com/tailscale/win and golang.org/x/sys/windows, so it cross-compiles with CGO_ENABLED=0.

The exported API mirrors the Wayland sibling package (github.com/go-vgo/robotgo/wayland) so callers can swap implementations per platform with a build tag.

Index

Constants

View Source
const (
	KeyA = "a"
	KeyB = "b"
	KeyC = "c"
	KeyD = "d"
	KeyE = "e"
	KeyF = "f"
	KeyG = "g"
	KeyH = "h"
	KeyI = "i"
	KeyJ = "j"
	KeyK = "k"
	KeyL = "l"
	KeyM = "m"
	KeyN = "n"
	KeyO = "o"
	KeyP = "p"
	KeyQ = "q"
	KeyR = "r"
	KeyS = "s"
	KeyT = "t"
	KeyU = "u"
	KeyV = "v"
	KeyW = "w"
	KeyX = "x"
	KeyY = "y"
	KeyZ = "z"

	Backspace = "backspace"
	Delete    = "delete"
	Enter     = "enter"
	Tab       = "tab"
	Esc       = "esc"
	Escape    = "escape"
	Up        = "up"
	Down      = "down"
	Right     = "right"
	Left      = "left"
	Home      = "home"
	End       = "end"
	Pageup    = "pageup"
	Pagedown  = "pagedown"

	F1  = "f1"
	F2  = "f2"
	F3  = "f3"
	F4  = "f4"
	F5  = "f5"
	F6  = "f6"
	F7  = "f7"
	F8  = "f8"
	F9  = "f9"
	F10 = "f10"
	F11 = "f11"
	F12 = "f12"

	Shift    = "shift"
	Ctrl     = "ctrl"
	Alt      = "alt"
	Cmd      = "cmd"
	ShiftL   = "shiftl"
	ShiftR   = "shiftr"
	CtrlL    = "ctrll"
	CtrlR    = "ctrlr"
	AltL     = "altl"
	AltR     = "altr"
	Space    = "space"
	Capslock = "capslock"
	Caps     = "caps"
	Print    = "print"
	Insert   = "insert"
	Menu     = "menu"
)

Key constants matching robotgo's API.

View Source
const Version = "v0.1.0-windows"

Version is the robotgo-win version string.

Variables

View Source
var ErrDriverNotInstalled = errors.New("robotgo: interception driver not installed or accessible")

ErrDriverNotInstalled is returned when the Interception driver is missing.

View Source
var ErrNotFound = errors.New("robotgo: window not found")

ErrNotFound is returned when no matching window is found.

View Source
var ErrNotSupported = errors.New("robotgo: operation not supported")

ErrNotSupported is returned when an operation is not supported.

View Source
var NotPid bool

NotPid, when true, makes the pid argument of the keyboard APIs be treated as a window handle (HWND) directly instead of a process id, mirroring the default Cgo backend's robotgo.NotPid behavior on Windows.

Functions

func ActiveName

func ActiveName(name string) error

ActiveName brings the first window whose title contains name (case insensitive) to the foreground.

func ActivePid added in v1.3.2

func ActivePid(pid int, isHandle bool) error

ActivePid restores (if minimized) and brings to the foreground the first visible window owned by pid, or the window pid itself when isHandle.

func Alert added in v1.3.4

func Alert(title, msg, ok, cancel string) bool

Alert shows a modal MessageBox and reports whether OK was chosen; like the Cgo backend it uses the stock OK/Cancel buttons (OK only when cancel is ""), so the ok label is ignored.

func Capture

func Capture(args ...int) (*image.RGBA, error)

Capture captures the screen and returns an *image.RGBA.

func CaptureImg

func CaptureImg(args ...int) (image.Image, error)

CaptureImg captures the screen and returns an image.Image. Optional args: x, y, w, h (region). With no args the full primary screen is captured.

func CheckAccess added in v1.2.0

func CheckAccess(prompt bool) bool

CheckAccess reports whether input injection is permitted. Windows has no accessibility gate, so it always returns true; prompt is ignored.

func Click

func Click(args ...interface{}) error

Click clicks a mouse button. Default is the left button. Use "left", "right", or "center". Pass true for a double-click.

func CloseHID added in v1.3.6

func CloseHID() error

CloseHID releases the Interception driver devices.

func CloseWindow

func CloseWindow(args ...int) error

CloseWindow closes a window by posting WM_CLOSE. With no args the foreground window is closed; otherwise the first arg is a pid, and pid <= 0 (e.g. a failed lookup) returns ErrNotFound. A nil error means the request was sent, not that the window has closed.

func CmdCtrl

func CmdCtrl() string

CmdCtrl returns "cmd" on macOS, "ctrl" elsewhere. On Windows: "ctrl".

func DisplaysNum

func DisplaysNum() int

DisplaysNum returns the number of displays.

func DragSmooth

func DragSmooth(x, y int, args ...interface{}) error

DragSmooth moves the mouse smoothly while holding a button down.

func FindIds

func FindIds(name string) ([]int, error)

FindIds finds PIDs whose executable name contains name (case insensitive).

func FindName

func FindName(pid int) (string, error)

FindName returns the executable name for a given PID.

func FindNames

func FindNames() ([]string, error)

FindNames returns all process names.

func FindPath

func FindPath(pid int) (string, error)

FindPath returns the full executable path for a PID.

func GetActiveApp added in v1.2.0

func GetActiveApp() (string, string, int)

GetActiveApp returns the foreground app's executable name, full executable path and pid. Fields that can not be resolved are left empty.

func GetBounds added in v1.3.2

func GetBounds(pid int, isHandle bool) (int, int, int, int)

GetBounds returns the window rect (x, y, w, h) of pid's window (an HWND when isHandle); pid <= 0 selects the foreground window. It returns zeros when no window is found.

func GetClient added in v1.3.2

func GetClient(pid int, isHandle bool) (int, int, int, int)

GetClient returns the client area (x, y, w, h) of pid's window in screen coordinates (pid is an HWND when isHandle); pid <= 0 selects the foreground window.

func GetHWNDByPid added in v1.3.4

func GetHWNDByPid(pid int) int

GetHWNDByPid returns the first visible top-level window owned by pid, 0 when there is none.

func GetMousePos

func GetMousePos() (int, int)

GetMousePos returns the current mouse position. Alias of Location.

func GetPid

func GetPid() int

GetPid returns the current process's PID.

func GetPixelColor

func GetPixelColor(x, y int, displayId ...int) string

GetPixelColor returns the pixel color at (x, y) as a 6-digit hex string.

func GetScaleSize

func GetScaleSize(displayId ...int) (int, int)

GetScaleSize returns the screen size multiplied by the DPI scale factor, matching robotgo.GetScaleSize on the Cgo backend.

func GetScreenSize

func GetScreenSize() (int, int)

GetScreenSize returns the primary display's width and height in pixels.

func GetTitle

func GetTitle(args ...int) string

GetTitle returns the title of the foreground window. Arguments are accepted for API parity but ignored.

func GetVersion

func GetVersion() string

GetVersion returns the robotgo version.

func Height

func Height(img image.Image) int

Height returns the height of an image.

func InitHID added in v1.3.6

func InitHID() error

InitHID opens the Interception driver devices. It is called by SetBackend(BackendHID) and lazily by HID input.

func InputClick added in v1.3.6

func InputClick(button string, double bool) error

InputClick clicks button through the current Backend.

func InputKeyToggle added in v1.3.6

func InputKeyToggle(key string, up bool, mods ...string) error

InputKeyToggle presses (up false) or releases key through the current Backend. Modifiers are pressed before the key and released after it; the modifiers the key itself implies (shift for "A" or "@") are added like KeyTap and KeyToggle do.

func InputMove added in v1.3.6

func InputMove(x, y int) error

InputMove moves the pointer to screen point (x, y) through the current Backend.

func InputPos added in v1.3.6

func InputPos() (int, int)

InputPos returns the pointer position the current Backend moves from: the virtual pointer under BackendMessage, otherwise the real cursor.

func InputScroll added in v1.3.6

func InputScroll(x, y int) error

InputScroll scrolls by wheel notches through the current Backend.

func InputToggle added in v1.3.6

func InputToggle(button string, up bool) error

InputToggle presses or releases button through the current Backend.

func InputType added in v1.3.6

func InputType(str string) error

InputType types str through the current Backend.

func KeyDown

func KeyDown(key string, args ...interface{}) error

KeyDown presses a key down. Extra args (e.g. modifiers) are forwarded to KeyToggle for API parity with the default robotgo backend.

func KeyPress

func KeyPress(key string, args ...interface{}) error

KeyPress presses a key (down + delay + up).

func KeyTap

func KeyTap(key string, args ...interface{}) error

KeyTap taps a key (press + release). Optional trailing modifiers (strings or a []string) and an int pid: when a pid is supplied the key (and its modifiers) is posted to that process's window via PostMessageW, mirroring the Windows path in key/keypress_c.h; otherwise it is injected into the focused window via SendInput. Set NotPid to pass an HWND instead of a pid.

KeyTap("a")
KeyTap("a", "ctrl")
KeyTap("a", "ctrl", "shift")
KeyTap("a", []string{"ctrl", "shift"})
KeyTap("a", pid)
KeyTap("a", pid, "ctrl")

func KeyToggle

func KeyToggle(key string, args ...interface{}) error

KeyToggle toggles a key. Default is "down"; pass "up" to release. Modifiers (strings or a []string) are pressed before the key and released in reverse order after it. An optional int pid posts the events to that process's window via PostMessageW, mirroring key/keypress_c.h; otherwise SendInput is used. Set NotPid to pass an HWND.

KeyToggle("a")
KeyToggle("a", "up")
KeyToggle("a", "down", []string{"ctrl", "shift"})
KeyToggle("a", "up", []string{"ctrl", "shift"})
KeyToggle("a", pid)

func KeyUp

func KeyUp(key string, args ...interface{}) error

KeyUp releases a key. Extra args (e.g. modifiers) are forwarded to KeyToggle for API parity with the default robotgo backend.

func Kill

func Kill(pid int) error

Kill kills a process by PID.

func Location

func Location() (int, int)

Location returns the current mouse position.

func MaxWindow

func MaxWindow(pid int, args ...interface{}) error

MaxWindow maximizes (or restores, if the bool arg is false) pid's window; pid <= 0 returns ErrNotFound instead of acting on the foreground window.

func MinWindow

func MinWindow(pid int, args ...interface{}) error

MinWindow minimizes (or restores, if the bool arg is false) pid's window; pid <= 0 returns ErrNotFound instead of acting on the foreground window.

func MouseDown

func MouseDown(key ...interface{}) error

MouseDown sends a mouse button down event.

func MouseUp

func MouseUp(key ...interface{}) error

MouseUp sends a mouse button up event.

func Move

func Move(x, y int, displayId ...int) error

Move moves the mouse to absolute position (x, y) through the current Backend. The optional displayId is accepted for API parity but ignored on Windows, where coordinates are in the unified virtual-desktop space.

func MoveClick

func MoveClick(x, y int, args ...interface{}) error

MoveClick moves to (x, y) then clicks.

func MoveRelative

func MoveRelative(x, y int) error

MoveRelative moves the mouse relative to its current position.

func MoveSmooth

func MoveSmooth(x, y int, args ...interface{}) bool

MoveSmooth moves the mouse smoothly to (x, y) with an ease-in-out curve. Optional args: steps (int), sleepMs (int). Returns true on success.

func PadHex

func PadHex(hex uint32) string

PadHex pads a hex color value to 6 characters.

func PidExists

func PidExists(pid int) (bool, error)

PidExists reports whether a process with the given PID exists.

func Pids

func Pids() ([]int, error)

Pids returns all process IDs.

func PostKeyTap added in v1.3.6

func PostKeyTap(w WindowInfo, key string, mods ...string) error

PostKeyTap taps key (with optional modifiers) in window w via WM_KEYDOWN/WM_KEYUP messages.

func PostKeyToggle added in v1.3.6

func PostKeyToggle(w WindowInfo, key, direction string, mods ...string) error

PostKeyToggle presses ("down") or releases ("up") key in window w. Modifiers are pressed before the key and released after it. Alt and Ctrl stay held in w until their "up", whichever of its controls has the focus. While Alt is held without Ctrl, keys posted in between are Alt chords (WM_SYSKEYDOWN) and that Alt releases as WM_KEYUP, while Alt released with no key in between is a lone Alt (WM_SYSKEYUP). An "up" for keys that were not pressed in w is posted as if they had just been pressed together.

func PostMouse added in v1.3.6

func PostMouse(w WindowInfo, ev MouseEvent) error

PostMouse posts a mouse message to the deepest child of window w under the event point. The real cursor does not move and the window is not activated.

func PostType added in v1.3.6

func PostType(w WindowInfo, text string) error

PostType types text into window w as WM_CHAR messages.

func Run

func Run(path string) ([]byte, error)

Run runs a shell command and returns its combined output.

func Save

func Save(img image.Image, path string, quality ...int) error

Save saves an image to a file. Format determined by extension.

func SaveCapture

func SaveCapture(path string, args ...int) error

SaveCapture captures the screen and saves it to a file.

func SaveJpeg

func SaveJpeg(img image.Image, path string, quality ...int) error

SaveJpeg saves an image as JPEG.

func SavePng

func SavePng(img image.Image, path string) error

SavePng saves an image as PNG.

func ScaleF

func ScaleF(displayId ...int) float64

ScaleF returns the system DPI scale factor (LOGPIXELSX / 96), mirroring the Cgo backend's sys_scale on Windows.

func Scroll

func Scroll(x, y int, args ...int) error

Scroll scrolls the mouse by wheel notches. Positive y scrolls up, negative scrolls down; positive x scrolls left, negative scrolls right (matching robotgo's Cgo backend convention). Optional arg: delay ms.

func ScrollDir

func ScrollDir(x int, direction ...interface{}) error

ScrollDir scrolls in a named direction: "up", "down", "left", "right".

func ScrollSmooth

func ScrollSmooth(to int, args ...int) error

ScrollSmooth scrolls the mouse smoothly by `to` steps, repeating `num` times (default 5) with `tm` ms between steps (default 100). An optional third arg sets the horizontal offset per step.

func SetBackend added in v1.3.6

func SetBackend(b Backend) error

SetBackend selects the input backend. BackendHID initializes the Interception driver immediately and fails if it is unavailable.

func SetHIDLibraryPath deprecated added in v1.3.6

func SetHIDLibraryPath(path string)

SetHIDLibraryPath is a no-op kept for compatibility.

Deprecated: the HID backend talks to the Interception driver directly and no longer loads interception.dll.

func SetMessageTarget added in v1.3.6

func SetMessageTarget(w WindowInfo)

SetMessageTarget fixes the window BackendMessage posts to. A zero WindowInfo restores automatic targeting.

func Toggle

func Toggle(key ...interface{}) error

Toggle toggles a mouse button down or up.

Toggle("left")        // press down
Toggle("left", "up")  // release

func Type

func Type(str string, args ...int) int

Type types a string using Unicode key events, supporting any character (including those not present on the current keyboard layout). An optional first int argument is the target pid: when non-zero each character is posted to that process's window as a WM_CHAR message, mirroring unicodeType() in key/keypress_c.h; otherwise it is injected into the focused window via SendInput. Set NotPid to pass an HWND instead of a pid.

Type("hello")
Type("hello", pid)

It returns the number of characters (runes) typed, stopping at the first failed input event; 0 if the target window is not found.

func TypeDelay

func TypeDelay(str string, delay int) error

TypeDelay types a string with a per-character delay in milliseconds.

func TypeStr

func TypeStr(str string, args ...int) error

TypeStr types a string, mirroring the robotgo API. It returns an error if not every character was typed.

func Width

func Width(img image.Image) int

Width returns the width of an image.

Types

type Backend added in v1.3.6

type Backend int

Backend selects how the global mouse and keyboard API injects input.

const (
	// BackendSendInput injects input with SendInput/SetCursorPos (default).
	BackendSendInput Backend = iota
	// BackendHID injects hardware-level strokes through the Interception
	// driver. Characters missing from the keyboard layout fall back to
	// SendInput Unicode events in Type.
	BackendHID
	// BackendMessage posts window messages (PostMessageW) without moving the
	// real cursor or activating a window. Mouse events go to the message
	// target, or the window under the event point when no target is set, and
	// use a virtual pointer started at the real cursor position. Key events
	// go to the target, or the foreground window.
	BackendMessage
)

func GetBackend added in v1.3.6

func GetBackend() Backend

GetBackend returns the current input backend.

type MouseEvent added in v1.3.6

type MouseEvent struct {
	Kind   MouseKind
	Button string // "left" (default), "right", "center"
	X, Y   int
	Clicks int // click state: 1 single, 2 posts a double-click message
	// DX, DY are scroll notches; positive DY scrolls up, positive DX scrolls
	// left, matching Scroll.
	DX, DY int
}

MouseEvent is one standalone mouse event at screen point (X, Y).

type MouseKind added in v1.3.6

type MouseKind int

MouseKind is the type of a standalone mouse event.

const (
	MouseMoved      MouseKind = iota // pointer moved (hover)
	MouseButtonDown                  // button pressed
	MouseButtonUp                    // button released
	MouseDragged                     // pointer moved while a button is held
	MouseScrolled                    // wheel scrolled by DX/DY lines
)

Standalone mouse event kinds.

type Nps

type Nps struct {
	Pid  int
	Name string
}

Nps represents a process.

func Process

func Process() ([]Nps, error)

Process returns all processes as []Nps.

type Point

type Point struct {
	X, Y int
}

Point represents a 2D point.

type Rect

type Rect struct {
	Point
	Size
}

Rect represents a rectangle.

func GetScreenRect

func GetScreenRect(displayId ...int) Rect

GetScreenRect returns the primary display rectangle, or the whole virtual desktop when a non-zero displayId is given on a multi-monitor system (the same rule as the Cgo backend's getScreenRect).

type Size

type Size struct {
	W, H int
}

Size represents a 2D size.

type WindowInfo added in v1.3.6

type WindowInfo struct {
	ID    uint64 `json:"id"`    // HWND
	Pid   int    `json:"pid"`   // owning process
	Owner string `json:"owner"` // executable name without ".exe"
	X     int    `json:"x"`
	Y     int    `json:"y"`
	W     int    `json:"width"`
	H     int    `json:"height"`
}

WindowInfo describes an on-screen top-level app window in screen coordinates.

func ListWindows added in v1.3.6

func ListWindows() ([]WindowInfo, error)

ListWindows returns visible, non-minimized top-level windows in z-order, front-most first. Windows of the calling process are excluded.

func WindowAt added in v1.3.6

func WindowAt(x, y int) (WindowInfo, error)

WindowAt returns the front-most app window containing screen point (x, y).

func (WindowInfo) Contains added in v1.3.6

func (w WindowInfo) Contains(x, y int) bool

Contains reports whether screen point (x, y) lies inside the window.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL