How can you send keys in console app programatically

G

GG

I have a console application that is using Console.Read() so that the
application does not exit.
I have a separate thread that is sleepeing for n-seconds and checks to
see if it is time to exit. When it is time to exit, the thread needs to
send keys to the console so it can continue and exit.
How can you send keyboard keys to a console application?


Thanks
 
B

Bob Grommes

GG,

Use System.Windows.Forms.SendKeys.SendWait(). You'll need to add a
reference to System.Windows.Forms to your solution. You can do this whether
your solution that's sending the keystroke(s) is a console app or a WinForms
app. I do this from a console app all the time, although in my case the
keys are being sent to a Win32 app.

Stepping back a bit though, you seem to be suggesting that the offending app
uses Console.Read(), suggesting that you have the source to that app; why
not simply remove the Console.Read(), or add some code to interpret a
command line argument to bypass interactive stuff and operate in a batch
mode? Sending keystrokes to another app is always problematic because you
not only have to send the keystroke, you have to make sure that window has
the focus, etc. You inevitably get into situations that break your SendKeys
solution -- the workstation behaves differently if it's locked, of other
apps are running, etc. Then you end up making Win32 calls via P/Invoke to
try to manage all that. It can get ugly fast, especially if the machine has
a user interacting with it at the time.

So, if there is any possible way to avoid using SendKeys, you really, really
should.

--Bob
 
N

Nicholas Paldino [.NET/C# MVP]

GG,

Instead of using Console.Read to keep the application from exiting, why
not use a ManualResetEvent? You can create it before your second thread
kicks off, and then have your main console thread wait for it to be set
(through a call to WaitOne). Then, in your worker thread, you would call
the Set method on the event, and your console thread would then continue to
run.

Hope this helps.
 
G

GG

Thanks Bob and Nicholas for the responses.
I will definately not use the Concole.Read since it may cause problems.
I will use Threading for this then.


Thanks again
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top