Win:Supress CTRL-C keyboard input

Post your FreeBASIC tips and tricks here. Please don’t post your code without including an explanation.
adele
Posts: 47
Joined: Jun 13, 2015 19:33

Win:Supress CTRL-C keyboard input

Postby adele » Feb 14, 2017 7:22

Code: Select all

'CtrlHandler.bas
'for windows, tested x64

' how to suppress program termination by keyboard CTRL-C or
' CTRL-BRK (in this example it DOES the break!)
' for
#include once "windows.bi"
#include once "crt\stdio.bi"

/'

st_w gave me this tip. Thank you. Danke.

very raw translation of the MSDN example.
please change it to your own needs.
  https://msdn.microsoft.com/en-us/library/windows/desktop/ms685049.aspx

'/



'Type fdwCtrlType As dword
 
'BOOL CtrlHandler( DWORD fdwCtrlType )
function  CtrlHandler( fdwCtrlType As DWORD  ) As BOOLean

Const CTRL_C_EVENT=0
Const CTRL_BREAK_EVENT=1
Const CTRL_CLOSE_EVENT=2
Const CTRL_LOGOFF_EVENT=5
Const CTRL_SHUTDOWN_EVENT=6
   
 
'  switch( fdwCtrlType )
  Select Case ( fdwCtrlType )
   ''  // Handle the CTRL-C signal.
    case CTRL_C_EVENT
      Printf( !"Ctrl-C event\n\n" )
      Beep ' ( 750, 300 )
      return( TRUE )
 
   ''  // CTRL-CLOSE: confirm that the user wants to exit.
    case CTRL_CLOSE_EVENT:
      Beep '( 600, 200 )
      printf( !"Ctrl-Close event\n\n" )
      return( TRUE )
 
   ''  // Pass other signals to the next handler.
    case CTRL_BREAK_EVENT:
      Beep '( 900, 200 )
      printf( !"Ctrl-Break event\n\n" )
      return FALSE
 
    case CTRL_LOGOFF_EVENT:
      Beep '( 1000, 200 )
      printf( !"Ctrl-Logoff event\n\n" )
      return FALSE
 
    case CTRL_SHUTDOWN_EVENT:
      Beep '( 750, 500 )
      printf( !"Ctrl-Shutdown event\n\n" )
      return FALSE
 
    default:
      return FALSE
  End Select
End Function 
 
'int main( void )



Function main() As long
   
 
  If ( SetConsoleCtrlHandler( /'(PHANDLER_ROUTINE)'/ @CtrlHandler, TRUE ) ) then
   
       printf( !"\nThe Control Handler is installed.\n" )
       printf( !"\n -- Now try pressing Ctrl+C or Ctrl+Break, or" )
       printf( !"\n    try logging off or closing the console...\n" )
       printf( !"\n(...waiting in a loop for events...)\n\n" )

    Print "Entering the LOOP, ESC leaves it."
    Print "CTRL-C is ignored."
    Print "BREAK with CTRL-BREAK"
    Do while( 1 )
       Var iStr=inkey()
       If iStr <> "" then
        Print Asc(iStr);" ";
        if iStr=Chr(27) Then Exit do         
       EndIf
    Loop
    print
 
  else
    printf( !"\nERROR: Could not set control handler")
    return 1
  EndIf

return 0
End Function

? main()
sleep



The comments are partly the original C/C++ code.
Have Fun!

Adi

Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 8 guests