使用我的C#应用程序从Google Chrome中获取文本

15

我正在编写一个小应用程序,其中之一的功能是在打字时将快捷方式扩展为完整文本。

例如:用户在某处写下“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 浏览器一起使用。

感谢您提前的任何反馈。


2
不确定是否是最佳方法,我会去https://developer.chrome.com/extensions/devguide。在我看来,这是可行的,但是挂钩到Web浏览器可能会触发防病毒软件。 - Cleptus
@bradbury9 在我们过于保护的反病毒软件中设置异常不是问题。 - Banana
1
如果您想在Web浏览器和WPF应用程序中实现此功能,您将需要创建一个键盘记录器,不断监视键盘并替换文本以模拟键盘输入。WPF控件没有Windows句柄,因此WinAPI对它们无用。Web浏览器中呈现的控件也一样。 - dymanoid
也许可以尝试创建一个谷歌浏览器扩展来实现这个目的。希望能有所帮助! - vCillusion
正如@dymanoid所建议的那样,对于Winforms和WPF应用程序,我们可以尝试创建键盘记录器并监视键盘。它也将处理Web浏览器的情况。 - vCillusion
显示剩余4条评论
2个回答

3

我个人会尝试创建一个Chrome喜欢的库。有很多可用的库,比如Kantu,它专为Chrome设计。

例如:TestCafe,Watir,SlimerJS。


1

我认为使用库不是你想要做的最佳方式。我会使用更适合浏览器DOM操作的库,比如Selenium


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接