Python找不到结构类的DWTime属性
在这里我的代码:
from ctypes import byref, c_uint, c_ulong, sizeof, Structure, windll
import ctypes
import random
import sys
import time
import win32api
class LASTINPUTINFO(Structure):
"""Мы импортировали необходимые модули и создали структуру LASTINPUTINFO
для хранения временной метки (в миллисекундах), обозначающей момент
обнаружения последнего события ввода в системе. """
fields_ = [
('cbSize', ctypes.c_uint),
('dwTime', ctypes.c_ulong)
]
def get_last_input():
"""Дальше создаем функцию get_last_input, чтобы, собственно, определить этот момент."""
struct_lastinputinfo = LASTINPUTINFO()
# Обратите
# внимание на то, что прежде чем выполнять вызов, переменную cbSize
# нужно инициализировать с использованием размера структуры.
struct_lastinputinfo.cbSize = sizeof(LASTINPUTINFO) #
# Затем мы
# вызываем функцию GetLastInputInfo, которая присваивает полю struct_
# lastinputinfo.dwTime временную метку.
windll.user32.GetLastInputInfo(byref(struct_lastinputinfo))
# Следующий шаг состоит в определении того,
# как долго проработала система. Для этого применяется вызов
# функции GetTickCount .
run_time = windll.kernel32.GetTickCount() #
# Переменная elapsed должна быть равна разности
# между временем работы системы и временем последнего ввода.
elapsed = run_time - struct_lastinputinfo.dwTime
print(f"[*] It's been {elapsed} milliseconds since the last event.")
return elapsed
# Небольшой
# фрагмент кода, размещенный в конце , позволяет выполнить простую проверку
while True: #
get_last_input()
time.sleep(1)
但是我收到此错误:
Trackback(最近的电话最后一次): 文件“ c:\ user \ user \ user \ pycharmprojects \ sandbox_detected \ sandbox_detect.py”,第49行,in get_last_input() 文件“ C:\ User \ User \ user \ pycharmprojects \ sandbox_detected \ sandbox_detect.py”,第41行,在get_last_input中 大量= run_time -struct_lastinputinfo.dwtime attributeError:'lastInputInfo'对象没有属性'dwtime'
对我有帮助。
upd:
@megaemailman谢谢,现在的代码不会引发异常,但是尚不清楚为什么它不能正常工作,并且仅显示此功能:
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
[*] It's been 0 milliseconds since the last event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码中还有很多关键错误(除了错误的凹痕 - 我认为这是一个格式化问题):
根据 [python.docs]:ctypes-结构和工会(强调是我的):
所以,它是 _fields _ ( lundscores ))
始终定义 argtypes 和 Restype 用于通过 ctypes 调用的功能。检查 [so]:c函数从python通过ctypes返回不正确的值(@cristifati的答案)有关更多详细信息
>
不是重要的详细信息
,但是在使用 winapi 时,请使用定义某些类型的 wintypes 模块(实际上是别名)
我对您的代码进行了一些改进:
移动了 cbsize 成员在初始化器中设置了,因此每次班级都会实例化
时,不再需要
code00.py :
输出(在移动鼠标和按键时运行程序):
There are a bunch of critical errors in your code (besides the wrong indentation - which I consider a formatting issue):
According to [Python.Docs]: ctypes - Structures and unions (emphasis is mine):
So, it's _fields_ (surrounded by UnderScores)
Always define argtypes and restype for the functions you call via CTypes. Check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) for more details
Not critical, but when working with WinAPI, use the WinTypes module which defines some types (which are practically aliases)
I modified your code with some improvements:
Moved the cbSize member set in the initializer, so it is no longer necessary every time the class gets instantiated
Exit when Esc is pressed
code00.py:
Output (run the program while moving mouse and pressing keys):