Home > Mobile >  Making Window Topmost with Python and/or Windows API
Making Window Topmost with Python and/or Windows API

Time:12-01

I'm trying to write a piece of code which finds a target window (returns its handler), brings it to top, and makes it topmost. The problem is that I cannot make the window topmost.

HWND_TOPMOST = -1
SWP_NOSIZE = 1
SWP_NOMOVE = 2
hwnd = ctypes.windll.user32.FindWindowW(None, title) # works OK
ctypes.windll.user32.BringWindowToTop(hwnd) # works OK
ctypes.windll.user32.SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE) # doesn't work

How to make the window topmost?

Note: I cannot install third-party libraries, modules, etc. Thus, I need to use Python native modules and/or Windows API.

CodePudding user response:

I've found a solution. It looks like ctypes cannot convert a negative int (HWND_TOPMOST) to HWND type. Thus, HWND function from ctypes.windtypes module should be used.

import ctypes.wintypes

ctypes.windll.user32.SetWindowPos(hwnd, ctypes.wintypes.HWND(HWND_TOPMOST), 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE)
  • Related