cygwinmintty

How can I detect focus lost in mintty under Cygwin?


Does mintty under Cygwin in any way support the events of losing and gaining focus?

I'm looking for the equivalent of WM_KILLFOCUS from Windows or autocmd FocusLost * call ... from gvim, but under Cygwin within the mintty terminal.


Solution

  • Provided there was no actual answer after a few days, I'm providing my own, thanks to @Philippe's comment about GetForegroundWindow.

    /* wait-focus-lost.cc */
    #include <iostream>
    #include <windows.h>
    
    int main()
    {
        const HWND initial_window = GetForegroundWindow();
        HWND current_window;
        while ((current_window = GetForegroundWindow()) == initial_window)
            Sleep(1);
        const auto title = new wchar_t[MAX_PATH*2];
        GetWindowTextW(current_window, title, MAX_PATH*2);
        std::wcout << title << std::endl;
    }
    

    Disclaimer: no error checking in above code

    This piece of code waits until the foreground window changes and prints out the title of the new foreground window to the mintty console.

    I can now use this executable in a bash script to wait before executing another action that depends on focus being stolen.


    Since my environment is Cygwin, I'm providing the Makefile in case someone comes along and tries to compile the above on their own:

    CXX = x86_64-w64-mingw32-g++
    CC = x86_64-w64-mingw32-gcc
    LDFLAGS = -static
    CXXFLAGS = -O2 -Wall -Wextra
    
    all: wait-focus-lost.exe
    wait-focus-lost.exe: wait-focus-lost
    

    NB: Because of the .exe extension, the extra rule is needed under Cygwin to leverage both make implicit rules and dependency checking. Using just all: wait-focus-lost works for compilation, but breaks dependency checking.