Einzelnen Beitrag anzeigen

Benutzerbild von himitsu
himitsu

Registriert seit: 11. Okt 2003
Ort: Elbflorenz
43.164 Beiträge
 
Delphi 12 Athens
 
#8

Re: SetConsoleCtrlHandler Verständnisfrage(n)

  Alt 23. Aug 2009, 16:29
mit Delphi 7 compiliert seh ich übrigens noch kurz das "und tschüß", egal ob im Debugger oder nicht
Delphi-Quellcode:
program Project1;

{$APPTYPE CONSOLE}

uses
  Windows,
  SysUtils;

var
  AppTerminated: Boolean;
  f: THandle;

procedure Log(txt: AnsiString);
var
  b: cardinal;
begin
  if f = INVALID_HANDLE_VALUE then exit; // no file no write
  txt := txt + #13#10;
  WriteFile(f, txt[1], Length(txt), b, nil);
end;

function ConCtrlHandler(dwCtrlType: DWORD): Bool; stdcall;
begin
  Result := True;

  case dwCtrlType of
    // CTRL+C signal was received, either from keyboard input
    CTRL_C_EVENT: log('App-Event: CTRL_C_EVENT');

    // CTRL+BREAK signal was received, either from keyboard input
    CTRL_BREAK_EVENT: log('App-Event: CTRL_BREAK_EVENT');

    // --> system sends to all processes attached to a console when the user closes the console
    CTRL_CLOSE_EVENT: log('App-Event: CTRL_CLOSE_EVENT');

    // system sends to all console processes when a user is logging off.
    CTRL_LOGOFF_EVENT: log('App-Event: CTRL_LOGOFF_EVENT');

    // system sends to all console processes when the system is shutting down
    CTRL_SHUTDOWN_EVENT: log('App-Event: CTRL_SHUTDOWN_EVENT');
  end;
  AppTerminated := True;
end;

begin
  f := CreateFile('log.txt', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ,
       nil, CREATE_ALWAYS, 0, 0);
  try
    log('--------------------------'#13#10'App: Start');

    AppTerminated := False;

    if SetConsoleCtrlHandler(@ConCtrlHandler, True) then log('App: Set CtrlHandler true')
      else log('App: Set CtrlHandler false');


    log('App: Working...');
    while not AppTerminated do
    begin
      Write('Working...'#32);
      sleep(100);
    end;

    writeln(#10#13);
    writeln('...und Tschuess!');
    sleep(500);

    log('App: End');
  finally
    closehandle(f);
  end;
end.
Code:
--------------------------
App: Start
App: Set CtrlHandler true
App: Working...
App-Event: CTRL_CLOSE_EVENT
App: End
WinXP SP3

VERY BAD CODE?
von der Funktion her, würde es so auf's Gleiche rauskommen

und dein Log würde unter Delphi2009 nur die Hälfte speichern


[add]
Zitat:
AssignFile(), Writeln(
das ist was Anderes, diese Funktionen haben zusätzlich zur WFC noch eine eigene 128 Byte-Cache via Delphi drin
Garbage Collector ... Delphianer erzeugen keinen Müll, also brauchen sie auch keinen Müllsucher.
my Delphi wish list : BugReports/FeatureRequests
  Mit Zitat antworten Zitat