Golang如何获取鼠标位置的像素颜色

Golang如何获取鼠标位置的像素颜色 你好,有没有办法获取屏幕上鼠标位置所在像素的颜色?

2 回复

你可以使用 Robotgo 包(GitHub - go-vgo/robotgo: RobotGo,Go 原生跨平台 GUI 自动化 @vcaesar

x, y := robotgo.GetMousePos()
color := robotgo.GetPixelColor(x, y)
fmt.Printf("Color of pixel at (%d, %d) is 0x%s\n", x, y, color)

更多关于Golang如何获取鼠标位置的像素颜色的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中获取鼠标位置像素颜色需要结合操作系统API。以下是使用Windows API的实现示例:

package main

import (
    "fmt"
    "syscall"
    "unsafe"
)

var (
    user32 = syscall.NewLazyDLL("user32.dll")
    gdi32  = syscall.NewLazyDLL("gdi32.dll")

    getCursorPos   = user32.NewProc("GetCursorPos")
    getDC          = user32.NewProc("GetDC")
    getPixel       = gdi32.NewProc("GetPixel")
    releaseDC      = user32.NewProc("ReleaseDC")
)

type POINT struct {
    X, Y int32
}

func GetPixelColor() (uint8, uint8, uint8, error) {
    var pt POINT
    ret, _, _ := getCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
    if ret == 0 {
        return 0, 0, 0, fmt.Errorf("获取鼠标位置失败")
    }

    hdc, _, _ := getDC.Call(0)
    if hdc == 0 {
        return 0, 0, 0, fmt.Errorf("获取设备上下文失败")
    }
    defer releaseDC.Call(0, hdc)

    color, _, _ := getPixel.Call(hdc, uintptr(pt.X), uintptr(pt.Y))
    rgb := int32(color & 0xFFFFFF)

    r := uint8(rgb & 0xFF)
    g := uint8((rgb >> 8) & 0xFF)
    b := uint8((rgb >> 16) & 0xFF)

    return r, g, b, nil
}

func main() {
    r, g, b, err := GetPixelColor()
    if err != nil {
        fmt.Println("错误:", err)
        return
    }
    fmt.Printf("RGB: (%d, %d, %d)\n", r, g, b)
}

对于跨平台解决方案,可以使用robotgo库:

package main

import (
    "fmt"
    "github.com/go-vgo/robotgo"
)

func main() {
    x, y := robotgo.GetMousePos()
    color := robotgo.GetPixelColor(x, y)
    fmt.Printf("位置: (%d, %d), 颜色: %s\n", x, y, color)
    
    // 获取RGB分量
    r, g, b := robotgo.GetPixelColor(x, y)
    fmt.Printf("RGB: #%02X%02X%02X\n", r, g, b)
}

安装robotgo:

go get github.com/go-vgo/robotgo

注意:在macOS上可能需要额外权限:

# 首次运行需要授权辅助功能权限
# 系统偏好设置 -> 安全性与隐私 -> 隐私 -> 辅助功能

Linux系统可能需要安装依赖:

# Ubuntu/Debian
sudo apt-get install libx11-dev libxtst-dev libpng++-dev

# Fedora
sudo dnf install libX11-devel libXtst-devel libpng-devel

这些方法都能实时获取鼠标所在位置的像素颜色值。

回到顶部