【问题标题】:Receiving a Windows message in Python - UnicodeEncodeError ...?在 Python 中接收 Windows 消息 - UnicodeEncodeError ...?
【发布时间】:2013-11-03 17:43:17
【问题描述】:

我有一个 Python 3.3 小脚本,可以成功发送 (SendMessage) 一条 WM_COPYDATA 消息(灵感来自 here,适用于 XYplorer):

import win32api
import win32gui
import struct
import array

def sendScript(window, message):
    CopyDataStruct = "IIP"
    dwData = 0x00400001                           #value required by XYplorer
    buffer = array.array("u", message)
    cds = struct.pack(CopyDataStruct, dwData, buffer.buffer_info()[1] * 2 + 1, buffer.buffer_info()[0])
    win32api.SendMessage(window, 0x004A, 0, cds)  #0x004A is the WM_COPYDATA id

message = "helloworld"    
sendScript(window, message)                       #I write manually the hwnd during debug

现在我需要编写一个接收器脚本,仍然使用 Python。这个answer 中的脚本似乎可以工作(在更正print() 表单中的所有print 语句之后)。 似乎,因为它打印出接收到的消息的所有属性(hwndwparamlparam 等)除了消息的内容。 我得到一个错误,UnicodeEncodeError。更具体地说,

Python WNDPROC handler failed
Traceback (most recent call last):
  File "C:\Python\xxx.py", line 45, in OnCopyData
    print(ctypes.wstring_at(pCDS.contents.lpData))
  File "C:\Python\python-3.3.2\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 10-13: character maps to <undefined>

我不知道如何解决它,也是因为我没有在消息中使用“花哨”字符,所以我真的不明白为什么会出现这个错误。我还尝试在print(ctypes.wstring_at(pCDS.contents.lpData)) 中设置不同长度的消息,以及简单地使用string_at,但没有成功(在后一种情况下,我获得了一个二进制字符串)。

【问题讨论】:

    标签: python character-encoding sendmessage


    【解决方案1】:

    ctypes.wstring(在print (ctypes.wstring_at(pCDS.contents.lpData)) 行中)可能不是发件人发送的字符串类型。尝试将其更改为:

    print (ctypes.string_at(pCDS.contents.lpData))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-09
      • 2010-10-17
      • 1970-01-01
      • 2020-04-17
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多