The keyboard plugin has outputs that you can map to a Mach4 output. See attached image. There is two options, one to disable keyboard, and another to disable keyboard inputs completely.
There is also a scr API call to return the window title which you can monitor in the PLC script and then if it does not equal the whatever is shown at the top of your window you can turn off the output.
scr.GetActiveWindowText()
Ok, I've ended up doing it for you

Just drop this in your PLC script. You will need to check the mapping of the keyboard enable in the outputs and modify the code. Also the search term "Mach 4" can be changed depending what is shown at the top of your window.
local windowText = scr.GetActiveWindowText() --Get the window title text
local find = string.find(windowText, "Mach 4") --Search for "Mach 4" in the window title.
local hKeyboardOutput = mc.mcSignalGetHandle(inst, mc.OSIG_OUTPUT1)
local keyboardOutputState = mc.mcSignalGetState(hKeyboardOutput)
if find ~= nil then
--"Mach 4" was found i.e. Window is active
if (keyboardOutputState == mc.MC_OFF) then --Only turn on the output if it is off
mc.mcSignalSetState(hKeyboardOutput, mc.MC_ON)
end
else
--"Mach 4" was not found i.e. window minimised or lost focus
if (keyboardOutputState == mc.MC_ON) then--Only turn off the output if it is on
mc.mcSignalSetState(hKeyboardOutput, mc.MC_OFF)
end
end