c# - 使用我的 c# 应用程序从谷歌浏览器中获取文本
问题描述
我正在编写一个小应用程序,其中包括在打字时将快捷方式扩展为全文。例如:用户在某处写“BNN”并按下相关的键盘组合,应用程序会将“BNN”替换为“Hi I am Banana”。
经过一些研究,我了解到可以使用它来完成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 窗体应用程序,但它不适用于 WPF 或浏览器,只是给了我 WPF 应用程序的标题或 chrome 中选项卡的标题。
例如,如果我在输入此问题时在此页面上运行应用程序,而不是问题的内容,我得到的文本是:
使用我的 c# 应用程序从谷歌浏览器内部获取文本 - 代码日志 - Google
可能是因为他们使用图形来渲染元素,而我不确定如何到达活动元素并阅读它的文本。
我只在问题的标题中提到了网络浏览器,因为这个工具主要用于网络浏览器。
提前感谢您的任何反馈。
解决方案
我个人会尝试创建一个 chrome 喜欢的库。有很多可用的工具,例如专门用于 Chrome 的 Kantu。
示例:TestCafe、Watir、SlimerJS
推荐阅读
- r - 根据ggplot2中的第一个方面对堆叠条进行排序
- reactjs - axios 未在生产中发送 X-CSRFToken 标头
- flutter - 如何使自定义范围滑块在不均匀的离散分区中颤动?
- flutter - Flutter如何通过for循环显示列表
- python - 避免类中 try/except 块的代码重复
- python - 在python中找到两个最大值的对象
- amazon-web-services - 在我配置 https 后,AWS DNS 默认路由 http
- java - 在 Jenkins 服务器上将 java x86 更改为 64 位
- django - Django ORM 无法从特定字段中获取值
- flutter - 当我运行命令“pub global activate stagehand”时,出现以下错误