You can try to use:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms648402%28v=vs.85%29.aspx.
With C#, you can use it through P/Invoke:
http://www.pinvoke.net/default.aspx/user32.getcaretpos.
Note that if some control with the caret is in focus, this function will return true, otherwise it will return false, so you can hide your keyboard.
Note the difference with Solution 1: there is no need to call any other function. This function gives you current caret position (if any) global to the desktop.
On little problem is: some applications can handle keyboard input, but not use "official" Windows caret API. But you can try it out to see how often it might be the case. For such cases, you can have an option to disable your auto-hide feature.
As to the virtual keyboard itself, it can have certain problems; so please see my advice on this topic in my past answers:
Application focus getting and losing,
Programming on BACKSPACE button,
Creating a Virtual Keyboard.
—SA