使用Python和Win32 API从记事本窗口读取内容时,SendMessage返回0
我正在制作一个从记事本窗口读取内容的程序,但它总是返回“ 0”。我试图通过多种方式做到这一点,所有这些都做了同样的事情,所以这就是我想到的。我做错了吗?
import win32gui
#Message for getting the text
WM_GETTEXT = 0x000D
hNotepad = win32gui.FindWindow("Notepad", None)
Window = win32gui.FindWindowEx(hNotepad, 0, "Notepad", None)
message = win32gui.SendMessage(Window, WM_GETTEXT, 0, 0)
print(message)
I'm making a program that reads contents from a notepad window but it always returns "0". I tried to do it by multiple ways and all of them did the same thing so this is what I came up with. Am I doing something wrong?
import win32gui
#Message for getting the text
WM_GETTEXT = 0x000D
hNotepad = win32gui.FindWindow("Notepad", None)
Window = win32gui.FindWindowEx(hNotepad, 0, "Notepad", None)
message = win32gui.SendMessage(Window, WM_GETTEXT, 0, 0)
print(message)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我测试了您的代码(在Win11上),您的问题是您不正确地使用Findwindowex,未找到编辑窗口的句柄, Findwindowex返回0。
您可以使用 spy ++工具查看正确的窗口名称。
在Win11中,您需要使用
“ Richeditd2dpt”
。在WIN10中,您需要使用
“编辑”
。编辑
使用 wm_getText ,
sendmessage
的返回值是复制的字符数,而不包括终止null字符。要获取编辑的文本内容,您需要定义一个变量来存储字符串。
sendmessage
的第三个参数是您要获得的长度,第四个参数是字符串。I tested your code (on win11), your problem is that you use FindWindowEx incorrectly, the handle of the edit window is not found, FindWindowEx returns 0.
You can use the SPY++ tool to see the correct window name.
In win11, you need use
"RichEditD2DPT"
.In win10, you need use
"Edit"
.EDIT
When you use WM_GETTEXT, the return value of
SendMessage
is the number of characters copied, not including the terminating null character.To get the Edited Text Content, you need to define a variable to store the string. The third parameter of
SendMessage
is the length you want to get, and the fourth parameter is to the string.