如何使用进程id查找正在运行的进程的路径((窗户)

2024-04-25 15:26:09 发布

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

我有一个小脚本,它扫描打开的窗口,当它发现一个word文档打开时,它必须获得文件的路径。但是怎么做呢?我找了很多,但似乎什么也没找到。我将感谢任何帮助。提前谢谢

from ctypes import *
import sys
from win32gui import GetWindowText, GetForegroundWindow
import win32gui
import win32clipboard
import os
import shutil
import time

user32   = windll.user32
kernel32 = windll.kernel32
psapi    = windll.psapi
current_window = None


def get_current_process():
    global current_window
    global process_id
    # get a handle to the foreground window
    hwnd = user32.GetForegroundWindow()

    # find the process ID
    pid = c_ulong(0)
    user32.GetWindowThreadProcessId(hwnd, byref(pid))

    # store the current process ID
    process_id = "%d" % pid.value

    # grab the executable
    executable = create_string_buffer("\x00" * 512)
    h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)

    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    # now read it's title
    window_title = create_string_buffer("\x00" * 512)
    length = user32.GetWindowTextA(hwnd, byref(window_title),512)

    # print out the header if we're in the right process

    print("\n")
    print("[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value))
    print("\n")



while True:
    get_current_process()
    time.sleep(10)

Tags: theimportidgettitlecurrentwindowprocess