首页 > 解决方案 > Pyglet 透明游戏覆盖失去焦点

问题描述

我正在尝试使用 Pyglet 在游戏之上创建一个叠加层。示例适用于 pygame,您可以与游戏进行交互,并且 pygame 仍然在窗口和您的游戏之上绘制。使用 pyglet,您可以获得透明覆盖,但是每当您单击游戏时,您都会失去 pyglet 窗口的焦点(这很好),并且绘图不再显示在其顶部。有没有办法解决这个问题?

我试过win32gui.BringWindowToTop(window._hwnd)了,不幸的是没有奏效。

#!/usr/bin/env python
import pyglet

import win32gui
import win32con
import win32api

from time import sleep
from pyglet import gl


rgb = lambda rgba: [x / 255.0 for x in rgba]


def get_game_window(hwnd_name="MyGame"):
    while True:
        try:
            hwnd = win32gui.FindWindow(None, hwnd_name)
            window_rect = win32gui.GetWindowRect(hwnd)
            x = window_rect[0] - 5
            y = window_rect[1]
            width = window_rect[2] - x
            height = window_rect[3] - y
            return x, y, width, height, hwnd
        except:
            pass
        sleep(0.5)


def create_overlay(game_window):
    window = pyglet.window.Window(
        game_window[2], game_window[3], vsync=0, style=pyglet.window.Window.WINDOW_STYLE_BORDERLESS
    )
    window.set_mouse_visible(False)
    win32gui.SetWindowLong(
        window._hwnd, win32con.GWL_EXSTYLE,
        win32gui.GetWindowLong(window._hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED
    )
    win32gui.SetLayeredWindowAttributes(window._hwnd, win32api.RGB(255, 0, 128), 0, win32con.LWA_COLORKEY)
    gl.glClearColor(*rgb((255, 0, 128, 0)))
    return window


def update(_, window, label):
    gl.glClearColor(*rgb((255, 0, 128, 0)))
    window.clear()
    label.draw()


def main():
    window = create_overlay(get_game_window())
    label = pyglet.text.Label('Hello, Overlay!',
                              font_name='Arial',
                              font_size=15,
                              x=window.width / 2,
                              y=window.height / 2,
                              anchor_x='center',
                              anchor_y='center')
    pyglet.clock.schedule_interval(update, .005, window=window, label=label)
    pyglet.app.run()


if __name__ == "__main__":
    main()

标签: pythonpyglet

解决方案


推荐阅读