我正在编写一个小应用程序,其中之一的功能是在打字时将快捷方式扩展为完整文本。
例如:用户在某处写下“BNN”,然后按下相关的键盘组合,该应用程序将用“Hi I am Banana”替换“BNN”。
经过一些研究,我了解到这可以使用user32.dll
来完成,实现此任务的过程如下:
1)获取活动窗口句柄
2)获取活动窗口线程句柄
3)将输入附加到活动线程上
4)获取聚焦控件句柄(+插入符位置,但这不是问题)
5)从活动线程中分离输入
6)使用其句柄从聚焦控件中获取文本
这是我目前的代码:
try
{
IntPtr activeWindowHandle = GetForegroundWindow();
IntPtr activeWindowThread = GetWindowThreadProcessId(activeWindowHandle, IntPtr.Zero);
IntPtr thisWindowThread = GetWindowThreadProcessId(this.Handle, IntPtr.Zero);
AttachThreadInput(activeWindowThread, thisWindowThread, true);
IntPtr focusedControlHandle = GetFocus();
AttachThreadInput(activeWindowThread, thisWindowThread, false);
if (focusedControlHandle != IntPtr.Zero)
{
TB_Output.Text += focusedControlHandle + " , " + GetText(focusedControlHandle) + Environment.NewLine;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
//...
//...
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetWindowThreadProcessId(int handle, out int processId);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
internal static extern int AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, bool fAttach);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern IntPtr GetFocus();
这适用于某些 Windows Forms 应用程序,但不适用于 WPF 或浏览器,只会给出 WPF 应用程序的标题或 Chrome 标签页的标题。
例如,在我撰写这个问题时运行此页面上的应用程序,而不是显示问题的内容,我得到的文本是:
Get text from inside google chrome using my c# app - Stack Overflow - Google
可能是因为它们使用图形来呈现元素,而我不确定如何获取活动元素并读取其文本。
我在问题标题中仅提到了 Web 浏览器,因为该工具将主要与 Web 浏览器一起使用。
感谢您提前的任何反馈。