How to send an “ENTER” key press to another applic

2019-02-14 12:27发布

问题:

I have code that launches an external application and automatically fills in a password prompt.

I want to automate the pressing of the "ENTER" key, so that the user does not have to click "OK".

How can I send the ENTER key to an external application?

Below is my code as it stands right now.

The first line to post the password to the application works fine.

The second line to send an ENTER key press has no effect at all.

I am using Delphi 2010.

    //now that we have the control handle, send the password to it
    SendMessage(AppHandle,WM_SETTEXT,0,Integer(PChar(pwd)));

    //and now push ENTER
    SendMessage(AppHandle,WM_KEYDOWN,0,Integer(PChar(#13)));

回答1:

Try this

PostMessage(AppHandle, WM_KEYDOWN, VK_RETURN, 0);

Bye.



回答2:

Quick answer. Duplicate your final SendMessage call using the WM_KEYUP event. Some systems only trigger when the key is released not when it is pushed.

Something to try until the real programmers respond. (:-)



回答3:

Try #13#10 instead of just #13.



回答4:

There are a couple of different ways that you can do what you want.

The first and easiest to detail is the SendKey32.pas file. This unit was specifically written to allow you to do just what your asking. This delphi.about.com article gives a good explanation about the unit and what it can do.

I've personally started using a different method because of some limitations I found in the SendKey32 stuff. The second method is Journal Playback messages. This is a type of Windows System Hook that allows you to send (keystroke) messages to the O/S and have it deal with all of the little fiddly stuff.

There is a unit I found online called hkSend.pas that has all of the necessary plumbing all setup into a single function call (SendKeys).

If you do a Google for it and look at the first couple of entries you'll find a copy of the .pas file and you can see what's involved. The person who wrote hkSend appears to have made it work in a similar fashion to SendKey32.pas but using Journal Playback instead.

HTH,

Ryan.