如何在Python中使用Win32 API?

65 投票
3 回答
117079 浏览
提问于 2025-04-15 12:24

我怎么在Python中使用win32 API? 有什么最简单的方法吗?
能不能给我一些例子?

3 个回答

8

在win32 Python中,有一些重要的功能可以使用,比如消息框。这是一个经典的例子,通常会有“确定”或“取消”这两个选项。

result = win32api.MessageBox(None,"Do you want to open a file?", "title",1)



  if result == 1:
     print 'Ok'
  elif result == 2:
     print 'cancel'

这个集合:

win32api.MessageBox(0,"msgbox", "title")
win32api.MessageBox(0,"ok cancel?", "title",1)
win32api.MessageBox(0,"abort retry ignore?", "title",2)
win32api.MessageBox(0,"yes no cancel?", "title",3)
26

PyWin32,正如@chaos提到的,是最受欢迎的选择;另外一个选择是ctypes,它是Python自带的标准库的一部分。比如,print ctypes.windll.kernel32.GetModuleHandleA(None)这段代码会显示当前模块(无论是EXE还是DLL)的模块句柄。如果你想看一个更详细的例子,说明如何用ctypes来访问win32的API,可以点击这里

47

PyWin32 是一个很不错的选择,但怎么用呢?一种方法是从你遇到的具体问题开始,尝试去解决它。PyWin32 提供了许多 Win32 API 函数的接口,你需要先确定一个具体的目标。

在我使用的 Python 2.5 版本(Windows 上的 ActiveState)中,win32 包里有一个 Demos 文件夹,里面装满了各种库的示例代码。

比如,这里有一个叫 CopyFileEx.py 的示例:

import win32file, win32api
import os


def ProgressRoutine(TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred,
    StreamNumber, CallbackReason, SourceFile, DestinationFile, Data):
    print Data
    print TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile
    ##if TotalBytesTransferred > 100000:
    ##    return win32file.PROGRESS_STOP
    return win32file.PROGRESS_CONTINUE

temp_dir=win32api.GetTempPath()
fsrc=win32api.GetTempFileName(temp_dir,'cfe')[0]
fdst=win32api.GetTempFileName(temp_dir,'cfe')[0]
print fsrc, fdst

f=open(fsrc,'w')
f.write('xxxxxxxxxxxxxxxx\n'*32768)
f.close()
## add a couple of extra data streams
f=open(fsrc+':stream_y','w')
f.write('yyyyyyyyyyyyyyyy\n'*32768)
f.close()
f=open(fsrc+':stream_z','w')
f.write('zzzzzzzzzzzzzzzz\n'*32768)
f.close()

operation_desc='Copying '+fsrc+' to '+fdst
win32file.CopyFileEx(fsrc, fdst, ProgressRoutine, operation_desc, False,   win32file.COPY_FILE_RESTARTABLE)

这个示例展示了如何使用 CopyFileEx 函数,以及其他一些函数(比如 GetTempPath 和 GetTempFileName)。通过这个例子,你可以大致了解如何使用这个库。

撰写回答