If you are using Linux, you can install Xmacro. With Xmacro you can create macro files with keystroke sequences. Not only just regular keystrokes, but you can actually make keystroke combinations like Alt F4 etc. Then you call the macro files with a shell script. I use this a lot to manipulate the buttons on the active applications on the students screens. I really love my Alt F4 script, if a student opens a browser I can immediately close it!
To be able to do this you should be familiar with shell scripts, and study the documentation for Xmacro.