如何将字符串发送到其他应用程序(包括 Microsoft Word)
我试图实现这一点,但没有得到好的结果。我使用 GetForegroundWindow()、AttachThreadInput(uint,uint,bool) 和 GetFocus() 函数将字符串发送到另一个窗口。它适用于记事本、写字板和其他应用程序,但不适用于 Microsoft Word。
int foregroundWindowHandle = GetForegroundWindow();
uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
uint currentThreadId = GetCurrentThreadId();
bool b = AttachThreadInput(remoteThreadId, currentThreadId, true);
int focused = GetFocus();
int d = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
b = AttachThreadInput(remoteThreadId, currentThreadId, false);
SendMessage(focused , WM_GETTEXT, builder.Capacity, builder);
clip = builder.ToString();
//Text operations...
SendMessage(focused, WM_SETTEXT, 0, builder);
这是我的代码,但它不适用于Word。我知道Word使用自定义控件,但我认为应该有另一种方法来处理这个问题。
例如: Windows 语音识别将文本发送到每个具有焦点的应用程序,即使它是 Word。我不认为他们手动输入。
我想使用 SendInputs 函数,但我不知道如何实现。
I was trying to accomplish this but did not get good results. I used GetForegroundWindow(), AttachThreadInput(uint,uint,bool) and GetFocus() functions to send the strings to another window. It works with Notepad, Wordpad and other applications, but not with Microsoft Word.
int foregroundWindowHandle = GetForegroundWindow();
uint remoteThreadId = GetWindowThreadProcessId(foregroundWindowHandle, 0);
uint currentThreadId = GetCurrentThreadId();
bool b = AttachThreadInput(remoteThreadId, currentThreadId, true);
int focused = GetFocus();
int d = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
b = AttachThreadInput(remoteThreadId, currentThreadId, false);
SendMessage(focused , WM_GETTEXT, builder.Capacity, builder);
clip = builder.ToString();
//Text operations...
SendMessage(focused, WM_SETTEXT, 0, builder);
That's the code I have, but it doesn't work with Word. I know that Word uses Custom Controls, but I think there should be another way to handle this.
For example:
Windows Speech Recognition sends text to every application which has focus even if it is Word. I don't think they made the inputs manually.
I thought to use the SendInputs function but I don't know how to make that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查以下是否有效;您只需要调用
SendString
。这应该适用于任何可以接收其窗口当前处于活动状态的文本的应用程序。除第一种方法外的所有代码均由 pinvoke.net 提供。
Check whether the following works; you just need to call
SendString
. This should work for any application that can receive text whose window is currently active.All code except the first method is courtesy of pinvoke.net.
Word 不使用响应
WM_TEXT
的标准编辑控件。要将文本插入 Word,您可以使用SendInput
伪造输入,或 COM 自动化,或 UI 自动化。最后一个选项,UI 自动化,将是我的选择,也是 MS 现在希望您这样做的方式。
Word doesn't use a standard edit control that responds to
WM_TEXT
. To poke text into Word you could useSendInput
to fake input, or COM automation, or UI Automation.The last of these options, UI Automation, would be my choice and is the way MS intend you to do this nowadays.