ctypes MessageBoxW返回意外的中文字符

2024-04-26 10:34:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码来显示弹出消息

if platform.system() == 'Windows':
    import ctypes

    def message_box(title, text, style):
        return ctypes.windll.user32.MessageBoxW(0, text, title, style)

if platform.system() == 'Windows':
    message_box('Error', 'Phat sinh loi Unicode, kiem tra chi tiet trong %s' % common.ERR_LOG_FILE, 0)

当我的应用程序在Windows7中运行时,弹出窗口包含所有意外的中文字符,而我的原始消息(在代码片段中)只包含字母字符。这是我第一次使用ctypes,很困惑。 有人来解释一下,帮我解决。在

popup result


Tags: 代码textimportbox消息messageiftitle
1条回答
网友
1楼 · 发布于 2024-04-26 10:34:29

我猜你用的是python2。Python2的字符串是字节字符串,并被封送为字节字符串(char*)。python3的字符串是Unicode字符串,被封送为宽字符串(wchar_t*)。如果不定义.argtypesctypes就不会进行错误检查,并且很乐意传递错误的类型。在

要在Python 2上调用MessageBoxW,请改为传递Unicode字符串,但最好定义.argtypes和{},这样ctypes可以键入check并在参数出错时告诉您:

#python2
import ctypes
from ctypes import wintypes as w

user32 = ctypes.WinDLL('user32')
MessageBox = user32.MessageBoxW
MessageBox.argtypes = w.HWND,w.LPCWSTR,w.LPCWSTR,w.UINT
MessageBox.restype = ctypes.c_int

MessageBox(None, u'message', u'title', 0)

相关问题 更多 >