programmatically press an enter key after starting .exe file in Matlab

Solution 1:

There is a way using Java from Matlab, specifically the java.awt.Robot class. See here.

Apparently there are two types of programs, regarding the way they work when called from Matlab with system('...'):

  1. For some programs, Matlab waits until the program has finished before running the next statement. This happens for example with WinRAR (at least in my Windows 7 machine).

  2. For other programs this doesn't happen, and Matlab proceeds with the next statement right after the external program has been started. An example of this type is explorer (the standard Windows file explorer).

Now, it is possible to return execution to Matlab immediately even for type 1 programs: just add & at the end of the string passed to system. This is standard in Linux Bash shell, and it also works in Windows, as discussed here.

So, you would proceed as follows:

robot = java.awt.Robot;
command = '"C:\Program Files (x86)\WinRAR\WinRAR"'; %// external program; full path
system([command ' &']); %// note: ' &' at the end
pause(5) %// allow some time for the external program to start
robot.keyPress (java.awt.event.KeyEvent.VK_ENTER); %// press "enter" key
robot.keyRelease (java.awt.event.KeyEvent.VK_ENTER); %// release "enter" key

Solution 2:

If your applications are only on Windows platform, you can try using .net objects.

The SendWait method of the SendKeys objects allows to send virtually any key, or key combination, to the application which has the focus, including the "modifier" keys like Alt, Shift, Ctrl etc ...

The first thing to do is to import the .net library, then the full syntax to send the ENTER key would be:

NET.addAssembly('System.Windows.Forms');
System.Windows.Forms.SendKeys.SendWait('{ENTER}'); %// send the key "ENTER"

If you only do it once the full syntax is OK. If you plan to make extensive use of the command, you can help yourself with an anonymous helper function.

A little example with notepad

%% // import the .NET assembly and define helper function
NET.addAssembly('System.Windows.Forms');
sendkey = @(strkey) System.Windows.Forms.SendKeys.SendWait(strkey) ;

%% // prepare a few things to send to the notepad
str1 = 'Hello World' ;
str2 = 'OMG ... my notepad is alive' ;
file2save = [pwd '\SelfSaveTest.txt'] ;
if exist(file2save,'file')==2 ; delete(file2save) ; end %// this is just in case you run the test multiple times.

%% // go for it
%// write a few things, save the file then close it.
system('notepad &') ;   %// Start notepad, without matlab waiting for the return value
sendkey(str1)           %// send a full string to the notepad
sendkey('{ENTER}');     %// send the {ENTER} key
sendkey(str2)           %// send another full string to the notepad
sendkey('{! 3}');       %// note how you can REPEAT a key send instruction
sendkey('%(FA)');       %// Send key combination to open the "save as..." dialog
pause(1)                %// little pause to make sure your hard drive is ready before continuing
sendkey(file2save);     %// Send the name (full path) of the file to save to the dialog
sendkey('{ENTER}');     %// validate
pause(3)                %// just wait a bit so you can see you file is now saved (check the titlebar of the notepad)
sendkey('%(FX)');       %// Bye bye ... close the Notepad

As explained in the Microsoft documentation the SendKeys class may have some timing issues sometimes so if you want to do complex manipulations (like Tab multiple times to change the button you actually want to press), you may have to introduce a pause in your Matlab calls to SendKeys.

Try without first, but don't forget you are managing a process from another without any synchronization between them, so timing all that can require a bit of trial and error before you get it right, at least for complex sequences (simple one should be straightforward).

In my case above for example I am running all my data from an external hard drive with an ECO function which puts it into standby, so when I called the "save as..." dialog, it takes time for it to display because the HDD has to wake up. If I didn't introduce the pause(1), sometimes the file path would be imcomplete (the first part of the path was send before the dialog had the focus).


Also, do not forget the & character when you execute the external program. All credit to Luis Mendo for highlighting it. (I tend to forget how important it is because I use it by default. I only omit it if I have to specifically wait for a return value from the program, otherwise I let it run on its own)


The special characters have a special code. Here are a few:

Shift          +
Control (Ctrl)  ^
Alt            %

Tab            {TAB}
Backspace      {BACKSPACE}, {BS}, or {BKSP}
Validation     {ENTER} or ~ (a tilde)
Ins Or Insert  {INSERT} or {INS}
Delete         {DELETE} or {DEL}

Text Navigation {HOME} {END} {PGDN} {PGUP}
Arrow Keys      {UP} {RIGHT} {DOWN} {LEFT}

Escape          {ESC}
Function Keys   {F1} ... {F16}
Print Screen    {PRTSC}
Break           {BREAK}

The full list from Microsoft can be found here

Solution 3:

There is a small javascript utility that simulates keystrokes like this on the Windows javascript interpreter.

Just create a js file with following code:

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));

then call it from Matlab after the necessary timeout like this:

system('c:\my\js\file\script.js {Enter}');

Can't test here now, but I think this should work...

Solution 4:

If you need to run a console-only program in a context that permits full DOS redirection, you can create a file called, say, CR.txt containing a carriage return and use the '<' notation to pipe the value into the program.

This only works if you can provide all the keyboard input can be recorded in the file. It fails dismally if the input has to vary based on responses.

An alternative is to duplicate the input (and possibly output) stream(s) for the program and then pipe data into and out of the program. This is more robust and can permit dynamic responses to the data, but will also likely require substantial effort to implement a robot user to the application.

Rog-O-Matic is an example of a large application completely controlled by a program that monitors screen output and simulates keyboard input to play an early (1980s) ASCII graphic adventure game.

The other responses will be required for GUI-based applications.

Solution 5:

Python package pywinauto can wait any dialog and click buttons automatically. But it's capable for native and some .NET applications only. You may have problems with pressing WPF button (maybe QT button is clickable - not checked), but in such case code like app.DialogTitle.wait('ready').set_focus(); app.DialogTitle.type_keys('{ENTER}') may help. Your case is quite simple and probably some tricks with pywinauto are enough. Is your "app with popup" 64-bit or 32-bit?

wait and wait_not functions have timeout parameter. But if you need precisely listener with potentially infinite loop awaiting popups, good direction is global Windows hooks (pyHook can listen mouse and keybd events, but cannot listen dialog opening). I'll try to find my prototype that can detect new windows. It uses UI Automation API event handlers... and... ops... it requires IronPython. I still don't know how to set UI Automation handler with COM interface from standard CPython.


EDIT (2019, January): new module win32hooks was implemented in pywinauto a while ago. Example of usage is here: examples/hook_and_listen.py.