使用WatiN脚本将键击(即Enter键)传递到应用程序中

我正在使用WatiN测试工具。 我可以使用WatiN脚本将键击(即按Enter键)传递给应用程序吗?

此选项在WatiR中可用。 这个选项在WatiN中可用吗?

编辑:经过进一步检查,我发现发送ENTER键的标准方式在WatiN中不起作用,就像在WatiR中一样。 您需要使用System.Windows.Forms.SendKeys

另外,我建议您下载WatiN Test Recorder

这是示例代码。

using(IE ie = new IE("http://someurl")) { TextField myTxt = ie.TextField(Find.ById("myTextBox")).TypeText("some value"); System.Windows.Forms.SendKeys.SendWait("{ENTER}"); } 

在Degree Dev Blog上有一篇非常好的博客文章

它解释了如何添加Enter press作为扩展方法,如下所示:

 public static class MyWatiNExtensions { [DllImport("user32.dll")] private static extern IntPtr SetFocus(IntPtr hWnd); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetForegroundWindow(IntPtr hWnd); public static void TypeTextQuickly(this TextField textField, string text) { textField.SetAttributeValue("value", text); } public static void PressEnter(this TextField textField) { SetForegroundWindow(textField.DomContainer.hWnd); SetFocus(textField.DomContainer.hWnd); textField.Focus(); System.Windows.Forms.SendKeys.SendWait("{ENTER}"); Thread.Sleep(1000); } } 

这使得在测试中按Enter键变得非常容易。

 browser.TextField("txtSearchLarge").PressEnter(); 
 var textUrl = ie.TextField("txtUrl"); textUrl.Focus(); textUrl.TypeText("www.mydomain.com"); Thread.Sleep(3000); textUrl.KeyDown((char)Keys.Down); textUrl.KeyDown((char)Keys.Down); textUrl.KeyDown((char)Keys.Enter); 

您必须使用System.Windows.Forms

为什么不做以下事情呢?

 using(IE ie = new IE("http://someurl")) { TextField myTxt = ie.TextField(Find.ById("myTextBox")).TypeText("some value"); TextField.KeyPress('\r'); \\ \r is a carriage return } 

我正在使用Watin进行测试

只要浏览器具有焦点,上述答案就可以正常工作,如果没有,那么SendKeys.SendWait会触发任何具有焦点的应用程序。

 ie.Eval("var e = $.Event('keydown');e.which = $.ui.keyCode.ENTER;$('#myTextBox').trigger(e);"); 

虽然有点笨拙,但无论如何都会触发输入。

试试这个:

 // This method is designed to simulate an end-user pressing the ENTER key. private void CheckKeys(object sender, KeyPressEventArgs e) { // Set the key to be pressed; in this case, the ENTER key. if (e.KeyChar == (char)13) { // ENTER key pressed. e.Handled = true; } } 

然后,当您需要模拟按下的ENTER键时,只需调用此方法。