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.

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
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...


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JAMESAuthor Commented:
You're a star, that's done it.

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


Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
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...
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.