views:

662

answers:

2

We have written an application that sits in the tray controlling OpenVPN as an extension to a bigger application.

If you run openvpn.exe on command line, you can press F4 to close it. We need to do send the same keypress from C#, but you can only send string values to StandardInput.

We have been forced to kill OpenVpn to close it, and this seems to be causing BSOD every now and then on Vista...

Here is a link to my post on MSDN that also describes the issue: MSDN Forums

Does anyone know how to send special keystrokes to a Process with StandardInput?

Or maybe a workaround to close OpenVPN more cleanly?

UPDATE:

The following do not work when passed to StandardInput.Write(), F1 key is in this example:

  • ConsoleKey.F1
  • "\x70" (Hex value for F1)
  • Convert.ToChar((int)ConsoleKey.F1)

We already properly redirect the input/output, because we can successfully pass username/password to OpenVPN with no problem.

UPDATE 2: Found this on some command line option documentation for OpenVPN:

--service exit-event [0|1] Should be used when OpenVPN is being automatically executed by another program in such a context that no interaction with the user via display or keyboard is possible. In general, end-users should never need to explicitly use this option, as it is automatically added by the OpenVPN service wrapper when a given OpenVPN configuration is being run as a service. exit-event is the name of a Windows global event object, and OpenVPN will continuously monitor the state of this event object and exit when it becomes signaled.

The second parameter indicates the initial state of exit-event and normally defaults to 0.

Multiple OpenVPN processes can be simultaneously executed with the same exit-event parameter. In any case, the controlling process can signal exit-event, causing all such OpenVPN processes to exit.

How would I use this in C#? Is the "exit-event" signaling they are mentioning a Mutex?

+1  A: 
StandardInput.Write(ConsoleKey.F4);

Obviously you have to get StandardIn for the process.

Stephan
This does not work, did you try it?If you go to the link I posted for MSDN, it explains this. I will update my question.
Jonathan.Peppers
A: 

If I run OpenVPN as the following:

"openvpn.exe --config PathToMyConfig.ovpn --service MyEventName 0"

Then the following C# code causes OpenVPN to exit cleanly:

EventWaitHandle resetEvent = EventWaitHandle.OpenExisting("MyEventName");

resetEvent.Set();

Props to consultutah, his comments helped quite a bit.

Jonathan.Peppers