windows 如何确保应用程序窗口始终位于顶部?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3678966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:13:46  来源:igfitidea点击:

How can I ensure that the application windows is always on top?

pythonwindows

提问by Bruno 'Shady'

I have a simple Python script that runs in a console windows.

我有一个在控制台窗口中运行的简单 Python 脚本。

How can I ensure that the console window is always on top and if possible resize it?

如何确保控制台窗口始终位于顶部并在可能的情况下调整其大小?

采纳答案by Mark

To do this with the cmd window, you'll probably have to invoke a lot of win32 calls.

要使用 cmd 窗口执行此操作,您可能必须调用大量 win32 调用。

  1. Enumerate all the windows using win32gui.EnumWindows to get the window handles
  2. Find the "window title" that matches how you run your program. For example, doubling clicking on a .py file on my system the window title is "C:\Python26\python.exe". Running it on a command line, it is called c:\Windows\system32\cmd.exe - c:\python26\python.exe test.py
  3. Using the appropriate title get the cmd window handle.
  4. Using win32gui.SetWindowPosmake your window a "top-most" window, etc...
  1. 使用 win32gui.EnumWindows 枚举所有窗口以获取窗口句柄
  2. 找到与您运行程序的方式相匹配的“窗口标题”。例如,双击我系统上的 .py 文件,窗口标题为“C:\Python26\python.exe”。在命令行上运行它,它被称为 c:\Windows\system32\cmd.exe - c:\python26\python.exe test.py
  3. 使用适当的标题获取 cmd 窗口句柄。
  4. 使用win32gui.SetWindowPos使您的窗口成为“最顶层”窗口等...


mport win32gui, win32process, win32con
import os

windowList = []
win32gui.EnumWindows(lambda hwnd, windowList: windowList.append((win32gui.GetWindowText(hwnd),hwnd)), windowList)
cmdWindow = [i for i in windowList if "c:\python26\python.exe" in i[0].lower()]
win32gui.SetWindowPos(cmdWindow[0][1],win32con.HWND_TOPMOST,0,0,100,100,0) #100,100 is the size of the window

回答by Bruno 'Shady'

Using Mark's answerI arrived at this:

使用马克的回答我得到了这个:

import win32gui
import win32con

hwnd = win32gui.GetForegroundWindow()
win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST,100,100,200,200,0)

回答by Jesse Dhillon

If you are creating your own window, you can use Tkinter to create an "always on top" window like so:

如果您要创建自己的窗口,则可以使用 Tkinter 创建一个“始终在顶部”的窗口,如下所示:

from Tkinter import *
root = Tk()
root.wm_attributes("-topmost", 1)
root.mainloop()

And then put whatever you want to have happen within the main loop.

然后把你想要发生的任何事情放在主循环中。

If you are talking about the command prompt window, then you will have to use some Windows-specific utilities to keep that window on top. You can try this script for Autohotkey.

如果您正在谈论命令提示符窗口,那么您将必须使用一些特定于 Windows 的实用程序来将该窗口保持在顶部。您可以为 Autohotkey 尝试此脚本