Hello I leave my thanks in advance if anyone can help me 😰. So my english is being translated by my keyboard so excuse the spelling mistakes.
It's been 5 months and I still haven't fixed it.
I made a little progress now I can read the value, but for that I have to open the cheat engine and copy this address that always changes, I wanted to know how do I find the calculation logic to find this address automatically.print in cheat-engine
from ast import Num
import ctypes as c
from ctypes import wintypes as w
import ctypes
from time import time
from ReadWriteMemory import ReadWriteMemory
import psutil
from typing import Any, List, NewType
import time
import os
process_name = "TheIsleClient-Win64-Shipping.exe"
pid = None
for proc in psutil.process_iter():
if process_name in proc.name():
pid = proc.pid
k32 = c.windll.kernel32
OpenProcess = k32.OpenProcess
OpenProcess.argtypes = [w.DWORD,w.BOOL,w.DWORD]
OpenProcess.restype = w.HANDLE
ReadProcessMemory = k32.ReadProcessMemory
ReadProcessMemory.argtypes = [w.HANDLE,w.LPCVOID,w.LPVOID,c.c_size_t,c.POINTER(c.c_size_t)]
ReadProcessMemory.restype = w.BOOL
WriteMemory = k32.WriteProcessMemory
WriteMemory.argtypes = [w.HANDLE,w.LPCVOID,w.LPVOID,c.c_size_t,c.POINTER(c.c_size_t)]
WriteMemory.restype = w.BOOL
GetLastError = k32.GetLastError
GetLastError.argtypes = None
GetLastError.restype = w.DWORD
CloseHandle = k32.CloseHandle
CloseHandle.argtypes = [w.HANDLE]
CloseHandle.restype = w.BOOL
while True:
processHandle2 = OpenProcess(0x20, False, pid)
processHandle = OpenProcess(0x10, False, pid)
#base 1D22EE665C0
offsets = [0x30, 0x250, 0x130, 0x20, 0x258, 0x260, 0x734]
addr = 0x227F820AA34 # .exe module base address
data = c.c_ulonglong()
bytesRead = c.c_ulonglong()
result = ReadProcessMemory(processHandle, addr, c.byref(data), c.sizeof(data), c.byref(bytesRead))
e = GetLastError()
#40A000000000002E
#000000C800000AF0
#0xc800000af0
#0x40800000000000c8
numHex = 0
numHex1 = 0
num = str(hex(data.value))
tam = len(num)
numR = num[tam-5:tam]
numHex = int(numR, 16)
verif = numHex
#print(numHex)
if numHex == verif:
os.system('cls')
print(numHex)
time.sleep(1)
if numHex == verif:
time.sleep(1)
else:
print(numHex)
'''
print("TESTE", numHex)
print("ESSE NUMERO: ", numR)
print('result: {}, err code: {}, bytesRead: {}'.format(result,e,bytesRead.value))
print('data: {:016X}'.format(data.value))
'''
CloseHandle(processHandle)
Related
I want to use Ctypes to enumerate the device, the following examples are C++ language I am not very good at converting, the following code is half of what I wrote
My question is how to conversion this
//Enumerate through all devices in Set
DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for (i=0;SetupDiEnumDeviceInfo(hDevInfo,i,
&DeviceInfoData);i++)
https://social.msdn.microsoft.com/forums/windowsdesktop/en-US/43ab4902-75b9-4c5c-9b54-4567c825539f/how-to-enumerate-hardware-devices-by-using-setupdi?forum=vcgeneral
import ctypes as ct
from ctypes import wintypes as w
SetupAPI = ct.WinDLL('SetupAPI')
SetupAPI.SetupDiGetClassDevsW.argtypes = w.LPVOID,w.PWCHAR,w.HWND,w.DWORD
SetupAPI.SetupDiGetClassDevsW.restype = w.HANDLE
SetupAPI.SetupDiEnumDeviceInfo.argtypes = w.HANDLE,w.DWORD,w.HANDLE
SetupAPI.SetupDiEnumDeviceInfo.restype = w.BOOLEAN
DIGCF_DEFAULT = 0x00000001
DIGCF_PRESENT = 0x00000002
DIGCF_ALLCLASSES = 0x00000004
DIGCF_PROFILE = 0x00000008
DIGCF_DEVICEINTERFACE = 0x00000010
ClassGuid = None
Enumerator = None
hwndParent = None
Flags = DIGCF_PRESENT | DIGCF_ALLCLASSES
DeviceInfoSet = None
MemberIndex = None
DeviceInfoData = None
class SP_DEVINFO_DATA(ct.Structure):
_fields_ = [
('cbSize',w.DWORD),
('ClassGuid',w.LPVOID),
('DevInst',w.DWORD),
('Reserved',w.ULONG),
]
SP_DEVINFO_DATA = SP_DEVINFO_DATA()
hDevInfo = SetupAPI.SetupDiGetClassDevsW(
ClassGuid,
Enumerator,
hwndParent,
Flags
)
SP_DEVINFO_DATA.cbSize = ct.sizeof(SP_DEVINFO_DATA)
DeviceInfoSet = hex(hDevInfo)
MemberIndex = 1
DeviceInfoData = ct.byref(SP_DEVINFO_DATA)
SetupDiEnumDeviceInfo = SetupAPI.SetupDiEnumDeviceInfo(
DeviceInfoSet,
MemberIndex,
DeviceInfoData
)
print(SetupDiEnumDeviceInfo)
Here's a complete, typesafe example to enumerate a particular device type, in this case USB host controllers:
import ctypes as ct
from ctypes import wintypes as w
import uuid
SetupAPI = ct.WinDLL('SetupAPI')
# ULONG_PTR is defined as an unsigned integer of the same size as a pointer on the OS,
# which is ct.ulonglong on 64-bit or ct.ulong on 32-bit. w.WPARAM happens to follow
# that same definition.
ULONG_PTR = w.WPARAM
# For type safety. A ctypes function will only accept HDEVINFO not any old HANDLE.
class HDEVINFO(w.HANDLE):
pass
# A class to initialize and print GUIDs
class GUID(ct.Structure):
_fields_ = (('Data1', ct.c_ulong),
('Data2', ct.c_ushort),
('Data3', ct.c_ushort),
('Data4', ct.c_ubyte * 8))
def __repr__(self):
return f"GUID('{self}')"
def __str__(self):
return (f'{{{self.Data1:08x}-{self.Data2:04x}-{self.Data3:04x}-'
f'{bytes(self.Data4[:2]).hex()}-{bytes(self.Data4[2:]).hex()}}}')
def __init__(self,guid=None):
if guid is not None:
data = uuid.UUID(guid)
self.Data1 = data.time_low
self.Data2 = data.time_mid
self.Data3 = data.time_hi_version
self.Data4[0] = data.clock_seq_hi_variant
self.Data4[1] = data.clock_seq_low
self.Data4[2:] = data.node.to_bytes(6,'big')
PGUID = ct.POINTER(GUID)
# See https://learn.microsoft.com/en-us/windows-hardware/drivers/install/guid-devinterface-usb-host-controller
GUID_DEVINTERFACE_USB_HOST_CONTROLLER = GUID('{3ABF6F2D-71C4-462A-8A92-1E6861E6AF27}')
class SP_DEVINFO_DATA(ct.Structure):
_fields_ = (('cbSize', w.DWORD),
('ClassGuid', GUID),
('DevInst', w.DWORD),
('Reserved', ULONG_PTR))
def __repr__(self):
return f'SP_DEVINFO_DATA(ClassGuid={self.ClassGuid}, DevInst={self.DevInst})'
# Per docs, the cbSize member must be set to the size of this structure.
def __init__(self):
self.cbSize = ct.sizeof(SP_DEVINFO_DATA)
PSP_DEVINFO_DATA = ct.POINTER(SP_DEVINFO_DATA)
SetupAPI.SetupDiGetClassDevsW.argtypes = PGUID, w.PWCHAR, w.HWND, w.DWORD
SetupAPI.SetupDiGetClassDevsW.restype = HDEVINFO
SetupAPI.SetupDiEnumDeviceInfo.argtypes = HDEVINFO, w.DWORD, PSP_DEVINFO_DATA
SetupAPI.SetupDiEnumDeviceInfo.restype = w.BOOL
SetupAPI.SetupDiDestroyDeviceInfoList.argtypes = HDEVINFO,
SetupAPI.SetupDiDestroyDeviceInfoList.restype = w.BOOL
DIGCF_DEFAULT = 0x00000001
DIGCF_PRESENT = 0x00000002
DIGCF_ALLCLASSES = 0x00000004
DIGCF_PROFILE = 0x00000008
DIGCF_DEVICEINTERFACE = 0x00000010
ClassGuid = GUID_DEVINTERFACE_USB_HOST_CONTROLLER
Enumerator = None
hwndParent = None
Flags = DIGCF_DEVICEINTERFACE | DIGCF_PRESENT
devinfo = SP_DEVINFO_DATA()
# Query for the device interface,
# then enumerate them one by one by incrementing a zero-based index
hDevInfo = SetupAPI.SetupDiGetClassDevsW(ClassGuid, Enumerator, hwndParent, Flags)
try:
MemberIndex = 0
while SetupAPI.SetupDiEnumDeviceInfo(hDevInfo, MemberIndex, ct.byref(devinfo)):
print(devinfo)
MemberIndex += 1
finally:
SetupAPI.SetupDiDestroyDeviceInfoList(hDevInfo)
Output:
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=144)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=137)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=17)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=78)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=24)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=98)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=123)
SP_DEVINFO_DATA(ClassGuid={36fc9e60-c465-11cf-8056-444553540000}, DevInst=41)
My system has eight USB host controllers and the class GUID matches:
On python3 using the windows API:
https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumeinformationw
How to get these values (file_system_flags, max_component_length and serial_number), ​through this function GetVolumeInformationW, without installing any other external modules?
import ctypes
kernel32 = ctypes.windll.kernel32
volumeNameBuffer = ctypes.create_unicode_buffer(1024)
fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
serial_number = None
max_component_length = None
file_system_flags = None
target_disk = 'C:\\'
rc = kernel32.GetVolumeInformationW(
ctypes.c_wchar_p(target_disk),
volumeNameBuffer, ctypes.sizeof(volumeNameBuffer),
serial_number,
max_component_length,
file_system_flags,
fileSystemNameBuffer, ctypes.sizeof(fileSystemNameBuffer)
)
mount_point = target_disk[:-1]
disk_label = volumeNameBuffer.value
fs_type = fileSystemNameBuffer.value
max_length = max_component_length
flags = file_system_flags
serial = serial_number
print(mount_point, disk_label, fs_type, max_length, flags, serial)
Complement:
And how do I convert filesystem flags into human readable format?
my_disk_flag = 0x3e706ff
hex_flags = [0x00000002, 0x00000001, 0x20000000, 0x00000010, 0x00040000, 0x00000008, 0x00080000, 0x00100000, 0x00020000, 0x00800000, 0x00400000, 0x00010000, 0x01000000, 0x00000080, 0x00000040, 0x00200000, 0x02000000, 0x00000004, 0x00008000, 0x00000020, 0x08000000]
str_flags = ['FILE_CASE_PRESERVED_NAMES', 'FILE_CASE_SENSITIVE_SEARCH', 'FILE_DAX_VOLUME', 'FILE_FILE_COMPRESSION', 'FILE_NAMED_STREAMS', 'FILE_PERSISTENT_ACLS', 'FILE_READ_ONLY_VOLUME', 'FILE_SEQUENTIAL_WRITE_ONCE', 'FILE_SUPPORTS_ENCRYPTION', 'FILE_SUPPORTS_EXTENDED_ATTRIBUTES', 'FILE_SUPPORTS_HARD_LINKS', 'FILE_SUPPORTS_OBJECT_IDS', 'FILE_SUPPORTS_OPEN_BY_FILE_ID', 'FILE_SUPPORTS_REPARSE_POINTS', 'FILE_SUPPORTS_SPARSE_FILES', 'FILE_SUPPORTS_TRANSACTIONS', 'FILE_SUPPORTS_USN_JOURNAL', 'FILE_UNICODE_ON_DISK', 'FILE_VOLUME_IS_COMPRESSED', 'FILE_VOLUME_QUOTAS', 'FILE_SUPPORTS_BLOCK_REFCOUNTING']
Create an instance of the type and pass it by reference. It is equivalent to declaring a local variable in C and passing its address, e.g. DWORD flags; and passing as &flags to be an output parameter.
It also help ctypes error checking by declaring the .argtypes and .restype of the function call, which is similar to declaring a C prototype. ctypes.wintypes has many pre-defined types for Windows.
I've also added an .errcheck attribute that automatically checks the return value and raises Windows exception based on the GetLastError() code, and an enumeration to process the flags into a readable format:
import ctypes as ct
from ctypes import wintypes as w
from enum import IntFlag
class FSFlags(IntFlag):
FILE_CASE_SENSITIVE_SEARCH = 0x00000001
FILE_CASE_PRESERVED_NAMES = 0x00000002
FILE_UNICODE_ON_DISK = 0x00000004
FILE_PERSISTENT_ACLS = 0x00000008
FILE_FILE_COMPRESSION = 0x00000010
FILE_VOLUME_QUOTAS = 0x00000020
FILE_SUPPORTS_SPARSE_FILES = 0x00000040
FILE_SUPPORTS_REPARSE_POINTS = 0x00000080
FILE_VOLUME_IS_COMPRESSED = 0x00008000
FILE_SUPPORTS_OBJECT_IDS = 0x00010000
FILE_SUPPORTS_ENCRYPTION = 0x00020000
FILE_NAMED_STREAMS = 0x00040000
FILE_READ_ONLY_VOLUME = 0x00080000
FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000
FILE_SUPPORTS_TRANSACTIONS = 0x00200000
FILE_SUPPORTS_HARD_LINKS = 0x00400000
FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000
FILE_SUPPORTS_USN_JOURNAL = 0x02000000
FILE_SUPPORTS_BLOCK_REFCOUNTING = 0x08000000
FILE_DAX_VOLUME = 0x20000000
def validate(result,func,args):
if not result:
raise ct.WinError(ct.get_last_error())
return None
dll = ct.WinDLL('kernel32',use_last_error=True)
dll.GetVolumeInformationW.argtypes = w.LPCWSTR,w.LPWSTR,w.DWORD,w.LPDWORD,w.LPDWORD,w.LPDWORD,w.LPWSTR,w.DWORD
dll.GetVolumeInformationW.restype = w.BOOL
dll.GetVolumeInformationW.errcheck = validate
volumeNameBuffer = ct.create_unicode_buffer(w.MAX_PATH + 1)
fileSystemNameBuffer = ct.create_unicode_buffer(w.MAX_PATH + 1)
serial_number = w.DWORD()
max_component_length = w.DWORD()
file_system_flags = w.DWORD()
target_disk = 'c:\\'
dll.GetVolumeInformationW(target_disk,
volumeNameBuffer, ct.sizeof(volumeNameBuffer),
ct.byref(serial_number),
ct.byref(max_component_length),
ct.byref(file_system_flags),
fileSystemNameBuffer, ct.sizeof(fileSystemNameBuffer))
mount_point = target_disk[:-1]
disk_label = volumeNameBuffer.value
fs_type = fileSystemNameBuffer.value
max_length = max_component_length.value
flags = FSFlags(file_system_flags.value)
serial = serial_number.value
print(f'{mount_point=}\n{disk_label=}\n{fs_type=}\n{max_length=}\n{flags=}\n{serial=}')
Output example:
mount_point='c:'
disk_label=''
fs_type='NTFS'
max_length=255
flags=<FSFlags.FILE_SUPPORTS_USN_JOURNAL|FILE_SUPPORTS_OPEN_BY_FILE_ID|FILE_SUPPORTS_EXTENDED_ATTRIBUTES|FILE_SUPPORTS_HARD_LINKS|FILE_SUPPORTS_TRANSACTIONS|FILE_NAMED_STREAMS|FILE_SUPPORTS_ENCRYPTION|FILE_SUPPORTS_OBJECT_IDS|1024|512|FILE_SUPPORTS_REPARSE_POINTS|FILE_SUPPORTS_SPARSE_FILES|FILE_VOLUME_QUOTAS|FILE_FILE_COMPRESSION|FILE_PERSISTENT_ACLS|FILE_UNICODE_ON_DISK|FILE_CASE_PRESERVED_NAMES|FILE_CASE_SENSITIVE_SEARCH: 65472255>
serial=3465270344
For future reference, I'll leave the complete code here on how to list all disks and get their fstab-like information
import ctypes as ct
import string
from ctypes import wintypes as w
from enum import IntFlag
from pathlib import Path
class FSFlags(IntFlag):
FILE_CASE_SENSITIVE_SEARCH = 0x00000001
FILE_CASE_PRESERVED_NAMES = 0x00000002
FILE_UNICODE_ON_DISK = 0x00000004
FILE_PERSISTENT_ACLS = 0x00000008
FILE_FILE_COMPRESSION = 0x00000010
FILE_VOLUME_QUOTAS = 0x00000020
FILE_SUPPORTS_SPARSE_FILES = 0x00000040
FILE_SUPPORTS_REPARSE_POINTS = 0x00000080
FILE_VOLUME_IS_COMPRESSED = 0x00008000
FILE_SUPPORTS_OBJECT_IDS = 0x00010000
FILE_SUPPORTS_ENCRYPTION = 0x00020000
FILE_NAMED_STREAMS = 0x00040000
FILE_READ_ONLY_VOLUME = 0x00080000
FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000
FILE_SUPPORTS_TRANSACTIONS = 0x00200000
FILE_SUPPORTS_HARD_LINKS = 0x00400000
FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000
FILE_SUPPORTS_USN_JOURNAL = 0x02000000
FILE_SUPPORTS_BLOCK_REFCOUNTING = 0x08000000
FILE_DAX_VOLUME = 0x20000000
def validate(result,func,args):
if not result:
raise ct.WinError(ct.get_last_error())
return None
dll = ct.WinDLL('kernel32',use_last_error=True)
dll.GetVolumeInformationW.argtypes = w.LPCWSTR,w.LPWSTR,w.DWORD,w.LPDWORD,w.LPDWORD,w.LPDWORD,w.LPWSTR,w.DWORD
dll.GetVolumeInformationW.restype = w.BOOL
dll.GetVolumeInformationW.errcheck = validate
volumeNameBuffer = ct.create_unicode_buffer(w.MAX_PATH + 1)
fileSystemNameBuffer = ct.create_unicode_buffer(w.MAX_PATH + 1)
serial_number = w.DWORD()
max_component_length = w.DWORD()
file_system_flags = w.DWORD()
lst_available_disks = [f'{d}:\\' for d in string.ascii_uppercase if Path(f'{d}:\\').exists()]
lst_disk_types = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_DIR', 'DRIVE_REMOVABLE', 'DRIVE_FIXED', 'DRIVE_REMOTE', 'DRIVE_CDROM', 'DRIVE_RAMDISK']
for target_disk in lst_available_disks:
disk_type_index = dll.GetDriveTypeW(target_disk)
dll.GetVolumeInformationW(target_disk,
volumeNameBuffer, ct.sizeof(volumeNameBuffer),
ct.byref(serial_number),
ct.byref(max_component_length),
ct.byref(file_system_flags),
fileSystemNameBuffer, ct.sizeof(fileSystemNameBuffer))
mount_point = target_disk
disk_label = volumeNameBuffer.value
fs_type = fileSystemNameBuffer.value
max_length = max_component_length.value
flags = FSFlags(file_system_flags.value)
serial = serial_number.value
if 'FILE_READ_ONLY_VOLUME' in str(flags):
read_write_status = 'ro'
else:
read_write_status = 'rw'
extra_tab_label = ''
if len(disk_label) < 8: extra_tab_label = '\t'
extra_tab_type = ''
if len(lst_disk_types[disk_type_index]) < 12: extra_tab_type = '\t'
print(f'{disk_label}{extra_tab_label}\t{mount_point}\t{fs_type}\t{max_length}\t{serial}\t{read_write_status},{lst_disk_types[disk_type_index]}{extra_tab_type}\t{flags=}\n')
Output (Just replaces disk serial with zeros):
Win10 C:\ NTFS 255 0000000000 rw,DRIVE_FIXED flags=<FSFlags.FILE_SUPPORTS_USN_JOURNAL|FILE_SUPPORTS_OPEN_BY_FILE_ID|FILE_SUPPORTS_EXTENDED_ATTRIBUTES|FILE_SUPPORTS_HARD_LINKS|FILE_SUPPORTS_TRANSACTIONS|FILE_NAMED_STREAMS|FILE_SUPPORTS_ENCRYPTION|FILE_SUPPORTS_OBJECT_IDS|1024|512|FILE_SUPPORTS_REPARSE_POINTS|FILE_SUPPORTS_SPARSE_FILES|FILE_VOLUME_QUOTAS|FILE_FILE_COMPRESSION|FILE_PERSISTENT_ACLS|FILE_UNICODE_ON_DISK|FILE_CASE_PRESERVED_NAMES|FILE_CASE_SENSITIVE_SEARCH: 65472255>
D:\ FAT32 255 0000000000 rw,DRIVE_FIXED flags=<FSFlags.FILE_SUPPORTS_ENCRYPTION|512|FILE_UNICODE_ON_DISK|FILE_CASE_PRESERVED_NAMES: 131590>
DRV061107 E:\ CDFS 110 0000000000 ro,DRIVE_CDROM flags=<FSFlags.FILE_SUPPORTS_OPEN_BY_FILE_ID|FILE_READ_ONLY_VOLUME|FILE_UNICODE_ON_DISK|FILE_CASE_SENSITIVE_SEARCH: 17301509>
Ventoy F:\ exFAT 255 0000000000 rw,DRIVE_REMOVABLE flags=<FSFlags.FILE_SUPPORTS_ENCRYPTION|512|FILE_UNICODE_ON_DISK|FILE_CASE_PRESERVED_NAMES: 131590>
VTOYEFI G:\ FAT 255 0000000000 rw,DRIVE_REMOVABLE flags=<FSFlags.FILE_SUPPORTS_ENCRYPTION|512|FILE_UNICODE_ON_DISK|FILE_CASE_PRESERVED_NAMES: 131590>
I need my python script to get windows monitor power state.
According to this link in StackOverflow, I can use RegisterPowerSettingNotification to get GUID_MONITOR_POWER_ON but I don't know how to implement it. The objective is to trigger events when the screen goes off.
I can access the funcion at ctypes.windll.user32.RegisterPowerSettingNotification but I need help to call it and get the messsages
RegisterPowerSettingNotification
Power Setting GUIDs
I am running Windows 10 and Python 3
Update:
I was able to call and register the window to receive messages but I'm still unable to get the information I need from it... I know that lparam is a pointer to a structure but I need to get information from it like the GUID PowerSetting and Data fields
import win32con
import win32api
import win32gui
import sys
import time
from ctypes import POINTER, windll
from comtypes import GUID
from ctypes.wintypes import HANDLE, DWORD
PBT_POWERSETTINGCHANGE = 0x8013
def log_info(msg):
""" Prints """
print(msg)
f = open("test.log", "a+")
f.write(msg + "\n")
f.close()
def wndproc(hwnd, msg, wparam, lparam):
print('.')
log_info("wndproc: %s\nw: %s\nl: %s" % (msg, wparam, lparam))
if msg == win32con.WM_POWERBROADCAST:
if wparam == win32con.PBT_APMPOWERSTATUSCHANGE:
log_info('Power status has changed')
if wparam == win32con.PBT_APMRESUMEAUTOMATIC:
log_info('System resume')
if wparam == win32con.PBT_APMRESUMESUSPEND:
log_info('System resume by user input')
if wparam == win32con.PBT_APMSUSPEND:
log_info('System suspend')
if wparam == PBT_POWERSETTINGCHANGE:
log_info('Power setting changed...')
#lparam is pointer to structure i need
if __name__ == "__main__":
log_info("*** STARTING ***")
hinst = win32api.GetModuleHandle(None)
wndclass = win32gui.WNDCLASS()
wndclass.hInstance = hinst
wndclass.lpszClassName = "testWindowClass"
messageMap = { win32con.WM_POWERBROADCAST : wndproc }
wndclass.lpfnWndProc = messageMap
try:
myWindowClass = win32gui.RegisterClass(wndclass)
hwnd = win32gui.CreateWindowEx(win32con.WS_EX_LEFT,
myWindowClass,
"testMsgWindow",
0,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
0,
0,
hinst,
None)
except Exception as e:
log_info("Exception: %s" % str(e))
if hwnd is None:
log_info("hwnd is none!")
else:
log_info("hwnd: %s" % hwnd)
register_function = windll.user32.RegisterPowerSettingNotification
guids_info = {
'GUID_MONITOR_POWER_ON' : '{02731015-4510-4526-99e6-e5a17ebd1aea}',
'GUID_SYSTEM_AWAYMODE' : '{98a7f580-01f7-48aa-9c0f-44352c29e5C0}',
'fake' : '{98a7f580-01f7-48aa-9c0f-44352c29e555}' # just to see if I get an error or a different return from function
}
hwnd_pointer = HANDLE(hwnd)
for name, guid_info in guids_info.items():
result = register_function(hwnd_pointer, GUID(guid_info), DWORD(0))
print('registering', name)
print('result:', result) # result is pointer to unregister function if I'm not mistaken
print()
print('\nEntering loop')
while True:
win32gui.PumpWaitingMessages()
time.sleep(1)
To make the code work it is needed the powerbroadcast_setting structure, a function declaration in ctypes with CFUNCTYPE and a cast from lparam to powerbroadcast_setting
Fully working code:
import win32con
import win32api
import win32gui
import time
from ctypes import POINTER, windll, Structure, cast, CFUNCTYPE, c_int, c_uint, c_void_p, c_bool
from comtypes import GUID
from ctypes.wintypes import HANDLE, DWORD
PBT_POWERSETTINGCHANGE = 0x8013
GUID_CONSOLE_DISPLAY_STATE = '{6FE69556-704A-47A0-8F24-C28D936FDA47}'
GUID_ACDC_POWER_SOURCE = '{5D3E9A59-E9D5-4B00-A6BD-FF34FF516548}'
GUID_BATTERY_PERCENTAGE_REMAINING = '{A7AD8041-B45A-4CAE-87A3-EECBB468A9E1}'
GUID_MONITOR_POWER_ON = '{02731015-4510-4526-99E6-E5A17EBD1AEA}'
GUID_SYSTEM_AWAYMODE = '{98A7F580-01F7-48AA-9C0F-44352C29E5C0}'
class POWERBROADCAST_SETTING(Structure):
_fields_ = [("PowerSetting", GUID),
("DataLength", DWORD),
("Data", DWORD)]
def wndproc(hwnd, msg, wparam, lparam):
if msg == win32con.WM_POWERBROADCAST:
if wparam == win32con.PBT_APMPOWERSTATUSCHANGE:
print('Power status has changed')
if wparam == win32con.PBT_APMRESUMEAUTOMATIC:
print('System resume')
if wparam == win32con.PBT_APMRESUMESUSPEND:
print('System resume by user input')
if wparam == win32con.PBT_APMSUSPEND:
print('System suspend')
if wparam == PBT_POWERSETTINGCHANGE:
print('Power setting changed...')
settings = cast(lparam, POINTER(POWERBROADCAST_SETTING)).contents
power_setting = str(settings.PowerSetting)
data_length = settings.DataLength
data = settings.Data
if power_setting == GUID_CONSOLE_DISPLAY_STATE:
if data == 0: print('Display off')
if data == 1: print('Display on')
if data == 2: print('Display dimmed')
elif power_setting == GUID_ACDC_POWER_SOURCE:
if data == 0: print('AC power')
if data == 1: print('Battery power')
if data == 2: print('Short term power')
elif power_setting == GUID_BATTERY_PERCENTAGE_REMAINING:
print('battery remaining: %s' % data)
elif power_setting == GUID_MONITOR_POWER_ON:
if data == 0: print('Monitor off')
if data == 1: print('Monitor on')
elif power_setting == GUID_SYSTEM_AWAYMODE:
if data == 0: print('Exiting away mode')
if data == 1: print('Entering away mode')
else:
print('unknown GUID')
return True
return False
if __name__ == "__main__":
print("*** STARTING ***")
hinst = win32api.GetModuleHandle(None)
wndclass = win32gui.WNDCLASS()
wndclass.hInstance = hinst
wndclass.lpszClassName = "testWindowClass"
CMPFUNC = CFUNCTYPE(c_bool, c_int, c_uint, c_uint, c_void_p)
wndproc_pointer = CMPFUNC(wndproc)
wndclass.lpfnWndProc = {win32con.WM_POWERBROADCAST : wndproc_pointer}
try:
myWindowClass = win32gui.RegisterClass(wndclass)
hwnd = win32gui.CreateWindowEx(win32con.WS_EX_LEFT,
myWindowClass,
"testMsgWindow",
0,
0,
0,
win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
0,
0,
hinst,
None)
except Exception as e:
print("Exception: %s" % str(e))
if hwnd is None:
print("hwnd is none!")
else:
print("hwnd: %s" % hwnd)
guids_info = {
'GUID_MONITOR_POWER_ON' : GUID_MONITOR_POWER_ON,
'GUID_SYSTEM_AWAYMODE' : GUID_SYSTEM_AWAYMODE,
'GUID_CONSOLE_DISPLAY_STATE' : GUID_CONSOLE_DISPLAY_STATE,
'GUID_ACDC_POWER_SOURCE' : GUID_ACDC_POWER_SOURCE,
'GUID_BATTERY_PERCENTAGE_REMAINING' : GUID_BATTERY_PERCENTAGE_REMAINING
}
for name, guid_info in guids_info.items():
result = windll.user32.RegisterPowerSettingNotification(HANDLE(hwnd), GUID(guid_info), DWORD(0))
print('registering', name)
print('result:', hex(result))
print('lastError:', win32api.GetLastError())
print()
print('\nEntering loop')
while True:
win32gui.PumpWaitingMessages()
time.sleep(1)
problem:
Traceback (most recent call last): File "C:\Users\Nutzer\Google
Drive\Code\Code\memory_read.py", line 26, in
byref(bytesRead)) ctypes.ArgumentError: argument 2: : long int too long to convert
code:
from ctypes import *
from ctypes.wintypes import *
PID = 4016
address = 0x6C532407C
OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle
PROCESS_ALL_ACCESS = 0x1F0FFF
datadummy = b'.'*200
buffer = c_char_p(datadummy)
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)
processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, int(PID))
ReadProcessMemory(processHandle,
address,
buffer,
bufferSize,
byref(bytesRead))
CloseHandle(processHandle)
I tried to change the bytesRead = c_ulong(0) to some other ctypes, but no success. Im on a Windows 8.1 System 64bit. I couldnt find any solution or similiar problems after hours of searching. Does someone know whats wrong here?
After a long time of fail and error I finally have an answer.
from ctypes import *
from ctypes.wintypes import *
import ctypes
OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle
PROCESS_ALL_ACCESS = 0x1F0FFF
pid = 2320
address = 0x00C98FCC
buffer = c_char_p(b"The data goes here")
val = c_int()
bufferSize = len(buffer.value)
bytesRead = c_ulong(0)
processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
memmove(ctypes.byref(val), buffer, ctypes.sizeof(val))
print("Success: " + str(val.value))
else:
print("Failed.")
CloseHandle(processHandle)
I have set up my Python page like so (extract):
import evernote.edam.userstore.constants as UserStoreConstants
import evernote.edam.type.ttypes as Types
from evernote.api.client import EvernoteClient
client = EvernoteClient(token=auth_token, sandbox=False)
note_store = client.get_note_store()
The problem comes with this code:
filter = note_store.NoteFilter
filter.setOrder(NoteSortOrder.UPDATED.getValue())
I would then go onto use note_store.findNotesMetadata. However, I get the error:
AttributeError: 'module' object has no attribute 'setOrder'
What am I doing wrong? I tried to adapt from the example given here
Here is a working example:
from evernote.api.client import EvernoteClient
from evernote.edam.notestore.ttypes import NoteFilter, NotesMetadataResultSpec
from evernote.edam.type.ttypes import NoteSortOrder
auth_token = 'your-token'
client = EvernoteClient(token=auth_token)
note_store = client.get_note_store()
updated_filter = NoteFilter(order=NoteSortOrder.UPDATED)
offset = 0
max_notes = 10
result_spec = NotesMetadataResultSpec(includeTitle=True)
result_list = note_store.findNotesMetadata(auth_token, updated_filter, offset, max_notes, result_spec)
# note is an instance of NoteMetadata
# result_list is an instance of NotesMetadataList
for note in result_list.notes:
print note.title
here is my FULL working code:
import os
import sys
import hashlib
import binascii
from datetime import datetime,timedelta
import logging
# sys.path.append("lib")
# sys.path.append("libs/evernote-sdk-python3")
sys.path.append("libs/evernote-sdk-python3/lib")
from evernote import *
from evernote.api import *
from evernote.api.client import *
from evernote.edam.limits import *
from evernote.edam.type import *
from evernote.edam.type.ttypes import *
from evernote.edam.notestore import *
from evernote.edam.notestore.ttypes import *
from evernote.edam.notestore.NoteStore import *
from evernote.edam.userstore import *
from evernote.edam.userstore.constants import *
ToProcessNotebook = "toProcess"
isSandbox=True
# isChina=False
isChina=True
AuthTokenDict = {
"sandbox": {
# China, https://sandbox.evernote.com/api/DeveloperToken.action
"yinxiang": "change_to_your_token",
# International
"evernote": "",
},
"production": {
"yinxiang": "",
"evernote": "",
},
}
ServiceHost = ""
AuthToken = ""
if isChina:
if isSandbox:
AuthToken = AuthTokenDict["sandbox"]["yinxiang"]
ServiceHost = "sandbox.yinxiang.com"
else:
AuthToken = AuthTokenDict["production"]["yinxiang"]
ServiceHost = "app.yinxiang.com"
else:
if isSandbox:
AuthToken = AuthTokenDict["sandbox"]["evernote"]
ServiceHost = "sandbox.evernote.com"
else:
AuthToken = AuthTokenDict["production"]["evernote"]
ServiceHost = "app.evernote.com"
gClient = None
gUserStore = None
gNoteStore = None
def init():
global gClient, gUserStore, gNoteStore
logFilename = "EvernoteToWordpress_%s.log" % (getCurDatetimeStr())
loggingInit(logFilename)
gClient = EvernoteClient(
token=AuthToken,
# sandbox=sandbox,
# china=china,
service_host=ServiceHost
)
logging.info("gClient=%s", gClient)
gUserStore = gClient.get_user_store()
logging.info("gUserStore=%s", gUserStore)
isVersionOk = gUserStore.checkVersion(
"Evernote EDAMTest (Python)",
EDAM_VERSION_MAJOR, # UserStoreConstants.EDAM_VERSION_MAJOR,
EDAM_VERSION_MINOR, # UserStoreConstants.EDAM_VERSION_MINOR
)
logging.info("Is my Evernote API version up to date? %s", isVersionOk)
gNoteStore = gClient.get_note_store()
logging.info("gNoteStore=%s", gNoteStore)
def EvernoteToWordpress():
"""Process evernote note into wordpress"""
global gClient, gUserStore, gNoteStore
notebookList = gNoteStore.listNotebooks()
notebookListLen = len(notebookList)
logging.info("Found %s notebooks:", notebookListLen)
for curNotebook in notebookList:
logging.info("\tguid=%s,name=%s", curNotebook.guid, curNotebook.name)
if curNotebook.name == ToProcessNotebook:
processNotes(curNotebook)
break
def processNotes(curNotebook):
"""Process each note"""
logging.info("curNotebook=%s", curNotebook)
# find all notes in notebook
searchOffset = 0
searchPageSize = 100
searchFilter = NoteStore.NoteFilter()
searchFilter.order = NoteSortOrder.UPDATED
searchFilter.ascending = False
searchFilter.notebookGuid = curNotebook.guid
logging.info("searchFilter=%s", searchFilter)
resultSpec = NotesMetadataResultSpec()
resultSpec.includeTitle = True
resultSpec.includeContentLength = True
resultSpec.includeCreated = True
resultSpec.includeUpdated = True
resultSpec.includeDeleted = True
resultSpec.includeNotebookGuid = True
resultSpec.includeTagGuids = True
resultSpec.includeAttributes = True
resultSpec.includeLargestResourceMime = True
resultSpec.includeLargestResourceSize = True
logging.info("resultSpec=%s", resultSpec)
# foundNoteResult = gNoteStore.findNotesMetadata(
# authenticationToken=AuthToken,
# filter=searchFilter,
# offset=searchOffset,
# maxNotes=pageSize,
# resultSpec=resultSpec
# )
foundNoteResult = gNoteStore.findNotesMetadata(AuthToken, searchFilter, searchOffset, searchPageSize, resultSpec)
logging.info("foundNoteResult=%s", foundNoteResult)
if __name__ == "__main__":
init()
EvernoteToWordpress()
Note: evernote sdk is download from Evernote SDK for Python 3
Latest code: crifanEvernote.py