• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 457
  • 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...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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