Registriert seit: 8. Mai 2005
Ort: Sondershausen
4.274 Beiträge
Delphi 6 Personal
|
Re: SetConsoleCtrlHandler Verständnisfrage(n)
23. Aug 2009, 16:59
Ach, ich musste mich erst einmal mit CreateFile rumschlagen
damit das Loggen nicht gepuffert wird.
Delphi-Quellcode:
program Test;
{$APPTYPE CONSOLE}
uses
Windows;
var
AppTerminated: Boolean;
f: cardinal;
procedure Log(txt: string);
var
b: cardinal;
a: array [0..255] of char;
begin
if not(f<>0) then exit; // no file no write
zeromemory(@a, sizeof(a));
lstrcpy(a, PCHAR(txt + #13#10));
writefile(f, a, lstrlen(a), 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
//////////////////// VERY BAD CODE ////////////////////
f := CreateFile('log.txt', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ,
nil, TRUNCATE_EXISTING, FILE_FLAG_WRITE_THROUGH, 0);
if f = ERROR_FILE_NOT_FOUND then
f := CreateFile('log.txt', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ,
nil, CREATE_NEW, FILE_FLAG_WRITE_THROUGH, 0);
//////////////////// ------------- ////////////////////
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');
closehandle(f);
end.
Die Loggdatei:
Code:
--------------------------
App: Start
App: Set CtrlHandler true
App: Working...
App-Event: CTRL_CLOSE_EVENT
Also wird das Ding mit dem X-Button regelrecht "abgeschossen".
|
|
Zitat
|