Skip to content

Instantly share code, notes, and snippets.

@ultrafunkamsterdam
Created September 26, 2022 10:56
Show Gist options
  • Save ultrafunkamsterdam/c0d92c416f313cfaa4f0f555871beb43 to your computer and use it in GitHub Desktop.
Save ultrafunkamsterdam/c0d92c416f313cfaa4f0f555871beb43 to your computer and use it in GitHub Desktop.
Python windows native console ctrl+c callback
from ctypes import wintypes as w
import ctypes as c
def handler( *args ):
print( 'Native console ctrl handler call:' , args )
return 0
HandlerRoutineType = c.WINFUNCTYPE( w.BOOL , w.DWORD )
SetConsoleCtrlHandler = c.windll.kernel32.SetConsoleCtrlHandler
SetConsoleCtrlHandler.argtypes = (HandlerRoutineType , w.BOOL)
SetConsoleCtrlHandler.restype = w.BOOL
chandler = HandlerRoutineType( handler )
retval = SetConsoleCtrlHandler( chandler , 1 )
def test():
n = 0
import time
print( 'ignoring default python keyboarditerrupt. so to quit this program hit CTRL C 3 times' )
while True:
try:
time.sleep( .001 )
except KeyboardInterrupt as e:
if n >= 3:
break
n += 1
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment