How to detect background color on hover Python?

Question:

Does anyone know, how you can detect the color on which you’re hovering with your cursor with python and returning the color to a string?

Asked By: YeagerCS

||

Answers:

Solution for Windows:

def get_cursor_color():
    # Get the cursor position
    pt = ctypes.wintypes.POINT()
    ctypes.windll.user32.GetCursorPos(ctypes.byref(pt))

    # Get the color of the pixel at the cursor position
    hdc = ctypes.windll.user32.GetDC(None)
    color = ctypes.windll.gdi32.GetPixel(hdc, pt.x, pt.y)

    # Release the device context
    ctypes.windll.user32.ReleaseDC(None, hdc)

    # Return the color as a tuple of (R, G, B) values
    return (color & 0xff, (color >> 8) & 0xff, (color >> 16) & 0xff)

print(get_cursor_color())

Solution for linux:

def get_cursor_color():
    # Open a connection to the X server
    display = Xlib.display.Display()
    screen = display.screen()

    # Get the root window and the color map
    root_window = screen.root
    colormap = screen.default_colormap

    # Query the X server for the cursor position
    pointer = display.query_pointer(root_window)
    x, y = pointer.root_x, pointer.root_y

    # Get the pixel at the cursor position
    pixel = root_window.get_image(x, y, 1, 1, Xlib.X.ZPixmap, 0xffffffff).data[0]

    # Convert the pixel value to an (R, G, B) tuple
    return colormap.query_color(pixel)._data

print(get_cursor_color())

The result is RGB values

Answered By: Pavlo Sharhan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.