使用Python和Win32 API从记事本窗口读取内容时,SendMessage返回0

发布于 2025-01-29 21:27:33 字数 357 浏览 0 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后知后觉 2025-02-05 21:27:33

我测试了您的代码(在Win11上),您的问题是您不正确地使用Findwindowex,未找到编辑窗口的句柄, Findwindowex返回0。

您可以使用 spy ++工具查看正确的窗口名称。

在Win11中,您需要使用“ Richeditd2dpt”

Window = win32gui.FindWindowEx(hNotepad, 0, "RichEditD2DPT", None)

在WIN10中,您需要使用“编辑”

Window = win32gui.FindWindowEx(hNotepad, 0, "Edit", None)

编辑

使用 wm_getText sendmessage的返回值是复制的字符数,而不包括终止null字符。

要获取编辑的文本内容,您需要定义一个变量来存储字符串。 sendmessage的第三个参数是您要获得的长度,第四个参数是字符串。

buffer=' '*255
hNotepad = win32gui.FindWindow("Notepad", None)
Window = win32gui.FindWindowEx(hNotepad, 0, "Edit", None)
message = win32gui.SendMessage(Window, WM_GETTEXT, 255, buffer)
print(buffer)

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.

enter image description here

In win11, you need use "RichEditD2DPT".

Window = win32gui.FindWindowEx(hNotepad, 0, "RichEditD2DPT", None)

In win10, you need use "Edit".

Window = win32gui.FindWindowEx(hNotepad, 0, "Edit", None)

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.

buffer=' '*255
hNotepad = win32gui.FindWindow("Notepad", None)
Window = win32gui.FindWindowEx(hNotepad, 0, "Edit", None)
message = win32gui.SendMessage(Window, WM_GETTEXT, 255, buffer)
print(buffer)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文