Finding which window has input focus

by Richard Russell, April 2010

The WINLIB5 (and WINLIB5A) libaries contain the PROC_setfocus routine which allows you to set the input focus to a specified child window (or the main output window). However, there is no related function to return the handle of the window which currently has input focus.

The code below implements just such a function. It returns the handle of the child window (or main output window) which currently has input focus. If none of the windows 'owned' by your program have input focus, the function returns zero:

        DEF FN_getfocus
        LOCAL H%, O%, W%
        SYS "GetWindowThreadProcessId", @hwnd%, 0 TO W%
        SYS "GetCurrentThreadId" TO O%
        SYS "AttachThreadInput", O%, W%, TRUE
        SYS "GetFocus" TO H%
        SYS "AttachThreadInput", O%, W%, FALSE
        = H%