Python的生产效率极高,通过使用pypiwin32模块可以快速调用windows API函数,结合Python的高效开发能力,同等时间内比C++能更快的达到目标,pypiwin32模块封装了Win32下的常用定义,函数方法等。
在Python安装路径下\AppData\Local\Programs\Python\Python38\Lib\site-packages 有帮助文档:PyWin32.chm
文件类API在模块win32file中,进程类API在模块win32process中,win32con定义了所有的常量,,一些难以分类的API则在模块win32api中(大部分是kernel32.dll导出的API)
ctypes 调用C库printf打印输出
>>> import ctypes
>>> # cdll = cdecl标准 windll = stdcall标准 linux则是调用 libc.so.6
>>> msvcrt = ctypes.cdll.LoadLibrary("C:\WINDOWS\system32\msvcrt.dll")
>>> msvcrt = ctypes.cdll.msvcrt
>>>
>>> string = "hello lyshark\n"
>>> string = string.encode("utf-8")
>>> msvcrt.printf(string)
hello lyshark
14
ctypes 调用messagebox输出:
>>> from ctypes import *
>>> user32 = windll.LoadLibrary("user32.dll")
>>> string = "Hello lyshark\n"
>>> string = string.encode("utf-8")
>>>
>>>user32.MessageBoxA(0,string,"ctypes".encode("utf-8"),0)
>>>
>>>user32 = windll.LoadLibrary("user32.dll")
>>>MessageBox = user32.MessageBoxA
>>>print(MessageBox(0,"hello lyshark".encode("utf-8"),"msgbox".encode("utf-8"),0))
ctypes 调用 kernel32
>>> kernel32 = windll.LoadLibrary("kernel32.dll")
>>> CreateProcess = kernel32.CreateProcessA
>>> ReadProcessMemory = kernel32.ReadProcessMemory
ctypes 声明结构体
from ctypes import *
class MyStruct(Structure):
_fields_ = [
("username",c_char*10),
("age",c_int),
("sex",c_long)
]
class MyUnion(Union):
_fields_ = [
("a_long",c_long),
("a_int",c_int),
("a_char",c_char*10)
]
MyStruct.username = "lyshark"
MyStruct.age = 22
print(MyStruct.username)
pywin32常用使用方式
>>> import win32api
>>> import win32con
>>>
>>> win32api.MessageBox(0,"hello lyshark","Msgbox",win32con.MB_OK)
1
>>> import win32process
# 打开记事本程序,获得其句柄
>>> handle = win32process.CreateProcess('c:\\windows\\notepad.exe',
'', None , None , 0 ,win32process. CREATE_NO_WINDOW , None , None ,
win32process.STARTUPINFO())
# 使用TerminateProcess函数终止记事本程序
>>> win32process.TerminateProcess(handle[0],0)
>>> import win32event
# 创建进程获得句柄
>>> handle = win32process.CreateProcess('c:\\windows\\notepad.exe',
'', None , None , 0 ,win32process. CREATE_NO_WINDOW , None , None ,
win32process.STARTUPINFO())
# 等待进程结束
>>> win32event.WaitForSingleObject(handle[0], -1)
0 # 进程结束的返回值
>>> import win32api
# 打开记事本程序,在后台运行,即显示记事本程序的窗口
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '','',0)
鼠标控制
import win32gui
import win32api
获取句柄
hwnd = win32gui.FindWindow(classname, titlename)
获取窗口左上角和右下角坐标
left, top, right, bottom = win32gui.GetWindowRect(hwnd)
获取某个句柄的类名和标题
title = win32gui.GetWindowText(hwnd)
clsname = win32gui.GetClassName(hwnd)
获取父句柄hwnd类名为clsname的子句柄
hwnd1= win32gui.FindWindowEx(hwnd, None, clsname,