从PID设置活动/前景窗口

2024-09-28 03:14:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将程序(已知PID)设置为top/active/foreground(不确定哪个最合适)。在

PID设置为windows进程PID

    handle = win32api.OpenProcess( win32con.PROCESS_ALL_ACCESS,
                        False, pid)
    win32gui.SetForegroundWindow(handle)
    win32gui.SetActiveWindow(handle)

我要么得到:

^{pr2}$

我意识到这是一个问题在处理,但我不确定我应该如何正确地得到工作处理。在


Tags: 程序access进程windowstopallprocesspid
2条回答

这项工作可以由pywinauto完成:

from pywinauto import Application
app = Application().connect(process=<pid>)
app.top_window().set_focus()

但它可能不适用于最小化应用程序。在

OpenProcess函数:

如果函数成功,则返回值是指定的过程和它可以用于任何需要进程句柄的函数中。在

SetForegroundWindow函数:

它的参数是一个窗口的句柄,应该被激活并带到前台。在

所以你需要这样的翻译:

HWND h = ::GetTopWindow(0 );
while ( h )
{
  DWORD pid;
  DWORD dwTheardId = ::GetWindowThreadProcessId( h,&pid);
         if ( pid == /*your process id*/ )
         {
              // here h is the handle to the window
              break;
         }
         h = ::GetNextWindow( h , GW_HWNDNEXT);
}

python版本:

^{pr2}$

注意:

But note that this can easily fail, because when you first launch the process, it probably doesn't have a window until a few milliseconds later. Without some means of synchronizing between the parent and child, there's really no way around this. (You can hack it by, say, sleeping for a second, but that has the same problem as any attempt to sleep instead of synchronizing—most of the time, it'll be way too long, reducing the responsiveness/performance of your code for no reason, and occasionally, when the computer is busy, it'll be too short and fail.)

真正解决这个问题的唯一方法是使用pywin32来创建进程,而不是使用标准的Python代码。然后你就掌握了这个过程。这意味着您可以等待子进程启动其窗口循环,然后只枚举该进程的窗口。在

相关问题 更多 >

    热门问题