• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 417
  • Last Modified:

SendKeys.Send/Wait only works first time!


I am using SendKeys.Send("hello world") to send a text string to an external application (eg. notepad) but it only works fine the first time but never again until you reset the controlling application.

I am "discovering" the handle for my target window, bringing it into foreground using unmanaged win32 calls which all seem fine.  I send my first string and it works great but after that it fails to send anything (that I can see).

I have this function on a button and each time I click it the target app. does indeed receive focus but no string is apparently sent.

I have used both the .Send and .SendWait methods but neither solves the problem.

Any thoughts?

Many thanks.

  • 2
1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
You may need a small delay after you set focus to your external app before sending your keystrokes to allow that window to fully receive the focus.  Otherwise your keys may be going somewhere else...

JAMESAuthor Commented:
You're a star, that's done it.

Thanks a million (or 500 anyway)....


Mike TomlinsonMiddle School Assistant TeacherCommented:
You'll have to play with the delay interval to find the ~best~ length...though it's not guaranteed to work everytime.

You could make a loop that polls the current foreground window using the GetForegroundWindow() API:

    public  static extern IntPtr  GetForegroundWindow();

and then sends the keys only after it has been brought to the front.

Of course you run the risk of getting into an infinite loop if for some reason the target window never becomes the foreground window...

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now