2010-02-05 37 views
4

我与SendKeys.Send发生奇怪的问题SendKeys的双键键入

基本上会发生这样的事情。我在google.com上关注了Internet Explorer,并且我调用了SendKeys.Send(“TestSample \ n”);它有时会以不可预知的方式发送一些密钥两次(如TeestSample或TestSSSample)。它发生在大约20%的时间。

此外,当我在字符串SendKeys.Send(“Test Sample \ n”)中包含空格时,除了一点之外,它同样是不可预测的。每次我这样做,它都会输入测试样本,进行谷歌搜索,但也滚动结果页面,因为我输入文本后按空格键。

有没有其他人看到过这种行为。它似乎没有以记事本的重点执行这种方式。

(这里要举例说明一些示例代码,将它放入一个窗体中的秒钟计时器中,DllImport定义位于类的顶部附近。)此应用程序在Google.com上大约20%的时间内失败的Internet Explorer(8.0)

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); 
    [DllImport("user32.dll")] 
    public static extern IntPtr GetForegroundWindow(); 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     IntPtr foreground = GetForegroundWindow(); 
     if (foreground != _currentForeground) 
     { 
      _currentForeground = foreground; 
      var titleBuilder = new StringBuilder(200); 
      GetWindowText(foreground, titleBuilder, 200); 
      string title = titleBuilder.ToString(); 
      Debug.WriteLine("Title of " + title); 
      if (title == "Google - Windows Internet Explorer") 
      { 
       Debug.WriteLine("Sending keys"); 
       SendKeys.Send("Test Sample\n"); 
      } 
      if (title == "Untitled - Notepad") 
       SendKeys.Send("Test notpad sample\n"); 
      Thread.Sleep(2000); 
     } 
    } 
    private IntPtr _currentForeground = IntPtr.Zero; 
+0

只是一个观察,但一般而言,您应该只使用的SendKeys作为一个绝对的最后一招,如果你不能通过某种 – 2010-02-05 21:00:13

+1

的自动化库实现你的目标你有没有找到解决这个问题呢?我还有一个问题,SendKeys有时会发送两次,但很难重现。 – 2011-12-21 18:44:03

+1

此问题可能是http://stackoverflow.com/questions/2346281/vb-net-sendkeys-letters-duplicate – 2014-03-17 00:34:17

回答

-1

您可以得到更好的服务找到的hWnd你想在新的数据写入,然后调用SetWindowTextW

[DllImport("user32.dll")] 
public static extern int SetWindowTextW(HandleRef hWnd, [MarshalAs(UnmanagedType.LPWStr)] string text); 

之后,发现该按钮的hWnd和发送WM_LBUTTONDOWN和WM_LBUTTONUP使用

[DllImport("user32.dll")] 
public static extern int PostMessage(HandleRef hWnd, WM msg, int wParam, int lParam); 

    WM_LBUTTONDOWN = 0x0201 
    WM_LBUTTONUP = 0x0202