如何为火狐的活动进程生成键盘文本



我可以使用以下方法将文本从我的 C# WinForm 应用程序发送到另一个应用程序(如记事本):

SendKeys.SendWait("Hello");

但我需要将文本发送到火狐中的 html 输入元素。有几种方法可以选择目标应用程序。这个SO问题使用的代码如下:

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);

将所需的应用程序设置为前台,以便接收文本。但这不适用于名为"firefox"的应用程序,可能是因为它根据任务管理器使用不是 1 个而是 4 个进程。

我尝试了另一种方法:在调用SendKeys.SendWait之前,只需像 Alt-Tab 一样切换回最后一个活动应用程序,使用这个 SO 问题中的代码,它适用于记事本和 Chrome 浏览器,但不适用于 Firefox。

这样做的目的是从连接到RS232端口的重量测量设备(秤)获取数据,到浏览器中的html输入元素。模拟键盘的原理通常与USB条形码扫描仪一起使用。

知道如何用火狐来做到这一点吗?

我是否走错了路,是否有许多不同的方法可以在键盘中获取文本?

你不能使用 WinForms WebBrowser 吗?还可以考虑使用Selenium WebDriver,它可以通过Nuget获得。我认为它完全符合您的需求。

这是文档中的一个例子:

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
// Requires reference to WebDriver.Support.dll
using OpenQA.Selenium.Support.UI;
class GoogleSuggest
{
static void Main(string[] args)
{
// Create a new instance of the Firefox driver.
// Note that it is wrapped in a using clause so that the browser is closed 
// and the webdriver is disposed (even in the face of exceptions).
// Also note that the remainder of the code relies on the interface, 
// not the implementation.
// Further note that other drivers (InternetExplorerDriver,
// ChromeDriver, etc.) will require further configuration 
// before this example will work. See the wiki pages for the
// individual drivers at http://code.google.com/p/selenium/wiki
// for further information.
using (IWebDriver driver = new FirefoxDriver())
{
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
// Find the text input element by its name
IWebElement query = driver.FindElement(By.Name("q"));
// Enter something to search for
query.SendKeys("Cheese");
// Now submit the form. WebDriver will find the form for us from the element
query.Submit();
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => d.Title.StartsWith("cheese", StringComparison.OrdinalIgnoreCase));
// Should see: "Cheese - Google Search" (for an English locale)
Console.WriteLine("Page title is: " + driver.Title);
}
}
}

最新更新