I hope the following answer is not too outrageous. It doesn't address how to find out which window is in focus, but:
Step one: learn C.
Step two: learn about X-Window programming (which will be in C).
Step three:
Code:
man XQueryTree
man XSendEvent
Hope this helps.