0
Follow
0
View

How do I always keep pygame window on top of screen regardless of clicking anywhere? [duplicate]

daisho0906 注册会员
2023-01-25 20:48

Getting current window position:

from ctypes import POINTER, WINFUNCTYPE, windll
from ctypes.wintypes import BOOL, HWND, RECT


# get our window ID:
hwnd = pygame.display.get_wm_info()["window"]

# Jump through all the ctypes hoops:
prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
paramflags = (1, "hwnd"), (2, "lprect")

GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)

# finally get our data!
rect = GetWindowRect(hwnd)
print "top, left, bottom, right: ", rect.top, rect.left, rect.bottom, rect.right

# bottom, top, left, right:  644 98 124 644

Putting the window on the foreground:

x = rect.left
y = rect.top
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)
daying303 注册会员
2023-01-25 20:48

There's a shorter solution using the same function:

from ctypes import windll
SetWindowPos = windll.user32.SetWindowPos

NOSIZE = 1
NOMOVE = 2
TOPMOST = -1
NOT_TOPMOST = -2

def alwaysOnTop(yesOrNo):
    zorder = (NOT_TOPMOST, TOPMOST)[yesOrNo] # choose a flag according to bool
    hwnd = pygame.display.get_wm_info()['window'] # handle to the window
    SetWindowPos(hwnd, zorder, 0, 0, 0, 0, NOMOVE|NOSIZE)
deathguy000 注册会员
2023-01-25 20:48

I found a solution that seems pretty well done:

#!/usr/bin/python
# -*- coding: utf-8 -*-


from ctypes import windll, Structure, c_long, byref #windows only


class RECT(Structure):
    _fields_ = [
    ('left',    c_long),
    ('top',     c_long),
    ('right',   c_long),
    ('bottom',  c_long),
    ]
    def width(self):  return self.right  - self.left
    def height(self): return self.bottom - self.top


def onTop(window):
    SetWindowPos = windll.user32.SetWindowPos
    GetWindowRect = windll.user32.GetWindowRect
    rc = RECT()
    GetWindowRect(window, byref(rc))
    SetWindowPos(window, -1, rc.left, rc.top, 0, 0, 0x0001)

Now in order to put a window on top, simply call onTop(pygame.display.get_wm_info()['window']) to handle your pygame window.

cyl821122 注册会员
2023-01-25 20:48

This worked for me

import win32gui
import win32con

win32gui.SetWindowPos(pygame.display.get_wm_info()['window'], win32con.HWND_TOPMOST, 0,0,0,0, win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)

The window doesn't move because I used the SWP_NOMOVE tag