有时候windows程序会出现”卡死”的情况,在任务管理器中一目了然。那么问题来了,万一程序在后台或者远程运行,要如何知道程序是否未响应呢?这里分享一个利用pywin32的实现方法。
获取windows窗口对应的进程ID
hWndList = []
# 获取窗口句柄
win32gui.EnumWindows(lambda hWnd, param: param.append(hWnd), hWndList)
# 迭代
for hWnd in hWndList:
# 获取窗口句柄对应的线程ID和进程ID
threadId, process_id = win32process.GetWindowThreadProcessId(hWnd)
print(threadId, process_id)
获取进程名和进程ID
# instance表示进程实例(可重名)
junk, instances = win32pdh.EnumObjectItems(None, None,'process', win32pdh.PERF_DETAIL_WIZARD)
proc_ids=[]
proc_dict={}
for instance in instances:
if instance in proc_dict:
proc_dict[instance] = proc_dict[instance] + 1
else:
proc_dict[instance]=0
for instance, max_instances in proc_dict.items():
for inum in range(max_instances+1):
hq = win32pdh.OpenQuery()
path = win32pdh.MakeCounterPath( (None,'process',instance, None, inum,'ID Process') )
counter_handle=win32pdh.AddCounter(hq, path)
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)
proc_ids.append((instance,str(val)))
win32pdh.CloseQuery(hq)
proc_ids.sort()
判断窗口是否未响应
# 迭代进程ID
for i in range(0, len(sys_ids)):
# 匹配进程ID和进程名
if(sys_ids[i] == process_id and process_name == proc_names[i]):
# 判断窗口状态
status = checkStatus(hWnd)
status_list.append(status)
status_code = -1
if(len(status_list)>=1):
status_code = set(status_list).pop()
部分代码来自网络,欢迎讨论。