简体   繁体   English

如何使用 Python 从 Windows 操作系统中的窗口标题中获取 PID?

[英]How do I get a PID from a window title in windows OS using Python?

I need to feed a PID from a window that I know the title of.我需要从我知道标题的窗口提供 PID。

It's an installer program that seems to change vital credentials when the first "next" button is programmatically pressed in my code.这是一个安装程序,当在我的代码中以编程方式按下第一个“下一步”按钮时,它似乎会更改重要凭据。

I think it does this because the window fades away and then fades back in again but when I click the back button and click next again it doesn't do it again.我认为这样做是因为窗口逐渐消失然后再次消失,但是当我单击后退按钮并再次单击下一步时,它不会再次执行此操作。

The first "next" button, the first time I click it, has a shield on it so I think it might have something to do with UAC.第一个“下一步”按钮,我第一次点击它时,上面有一个盾牌,所以我认为它可能与 UAC 有关。

I am sending the window a ENTER keyboard press with this code:我正在使用以下代码向窗口发送 ENTER 键盘按键:

import win32com.client


shell = win32com.client.Dispatch("WScript.Shell")


def setwindowfocus(windowname):  # can be the window title or the windows PID

    shell.AppActivate(windowname)


def sendkeypresstowindow(windowname, key):

    setwindowfocus(windowname)
    shell.SendKeys(key)
    time.sleep(0.1)


sendkeypresstowindow(u'Some Known Window Title', '{ENTER}')
time.sleep(5)  # Wait for next window
sendkeypresstowindow(u'Some Known Window Title', '{ENTER}')
time.sleep(5)  # Wait for next window

The shell.AppActivate() can take a pid also so I was wondering how I would get that if the only information I have is the windows title. shell.AppActivate()也可以使用 pid,所以我想知道如果我拥有的唯一信息是 Windows 标题,我将如何获得它。

I have tried using pywinauto and run into the same problem, besides many of the members that should not be accessible in pywinauto are and its very unintuitive as to what I need to do to use it so I would rather steer clear of it until the code is cleaned up..我已经尝试使用 pywinauto 并遇到了同样的问题,除了许多不应该在 pywinauto 中访问的成员之外,它对于我需要做什么来使用它非常不直观,所以我宁愿避开它,直到代码被清理了。。

I also noticed that the handle of the window changes so If I can somehow get the handle from the window title and then the PID from the handle that would work also.我还注意到窗口的句柄发生了变化,所以如果我能以某种方式从窗口标题中获取句柄,然后从句柄中获取 PID 也可以使用。

The GetWindowThreadProcessId function seems to do what you want for getting a PID from a HWND. GetWindowThreadProcessId函数似乎可以执行您想要从 HWND 获取 PID 的操作。 And FindWindow is the usual way to find a window using its title. FindWindow 是使用标题查找窗口的常用方法。 So the following gets a所以下面得到一个

import win32gui,win32process
def get_window_pid(title):
    hwnd = win32gui.FindWindow(None, title)
    threadid,pid = win32process.GetWindowThreadProcessId(hwnd)
    return pid

I wonder if you should be trying to use UI Automation though if you are trying to drive the UI.我想知道您是否应该尝试使用UI 自动化,但如果您正在尝试驱动 UI。 I've not tried to use that via Python.我没有尝试通过 Python 使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM