Python 2.6 中 ctypes 的帮助

1 投票
3 回答
2985 浏览
提问于 2025-04-15 12:18

我好像没法让这段代码正常工作,我原以为我做得没错。

from ctypes import *


kernel32 = windll.kernel32

string1 = "test"
string2 = "test2"

kernel32.MessageBox(None,
                       string1,
                       string2,
                       MB_OK)

** 我试着按照下面的建议把它改成 MessageBoxA **

** 但是我遇到的错误是 :: **

Traceback (most recent call last):
  File "C:\<string>", line 6, in <module>
  File "C:\Python26\Lib\ctypes\__init__.py", line 366, in __getattr__
    func = self.__getitem__(name)
  File "C:\Python26\Lib\ctypes\__init__.py", line 371, in __getitem__
    func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'MessageBoxA' not found

3 个回答

0

哦,如果你不确定某个调用是需要kernel32还是user32之类的东西,不要害怕去MSDN上查找。那里有一个按字母排序的列表,还有一个按类别排序的列表。希望这些对你有帮助。

0

问题在于你想调用的函数其实并不叫 MessageBox()。实际上有两个函数,一个叫 MessageBoxA(),另一个叫 MessageBoxW()。前者处理的是8位的ANSI字符串,后者处理的是16位的Unicode(宽字符)字符串。在C语言中,预处理器符号 MessageBox 会根据是否启用了Unicode(具体来说,就是看 _UNICODE 这个符号是否被定义)来定义为 MessageBoxAMessageBoxW

其次,根据 MessageBox() 的文档MessageBoxA/W 是在 user32.dll 这个文件里,而不是在 kernel32.dll 里。

你可以试试这个(我现在不能验证,因为我没有在Windows电脑前):

user32 = windll.user32
user32.MessageBoxA(None, string1, string2, MB_OK)
4

MessageBox 是在 user32 里定义的,而不是在 kernel32 里,你也没有定义 MB_OK,所以用这个代替

windll.user32.MessageBoxA(None, string1, string2, 1)

另外,我建议你使用 python win32 API,因为它包含了所有常量和命名函数

编辑:我的意思是用这个

from ctypes import *

kernel32 = windll.kernel32

string1 = "test"
string2 = "test2"

#kernel32.MessageBox(None, string1, string2, MB_OK)
windll.user32.MessageBoxA(None, string1, string2, 1)

你也可以用 win32 API 做同样的事情,如下所示

import win32gui
win32gui.MessageBox(0, "a", "b", 1)

撰写回答