-
1
- #1
I was going through some of my old code and found this - I don't know how useful it might be to anyone, but hopefully it can be useful to someone.
What it does is demonstrates a function that detects the presence of a console (i.e. user opened command prompt or program was shelled to). What it does when I run it is if I'm in the console it will return a message on the console, else it will show a dialog box. Note: This is not compiled in console mode or with {$APPTYPE CONSOLE} as a parm. Idealistically, this should allow a multi-format app, if desired.
(It should go without saying from looking at the source, but the API function used works in Windows XP or above)
What it does is demonstrates a function that detects the presence of a console (i.e. user opened command prompt or program was shelled to). What it does when I run it is if I'm in the console it will return a message on the console, else it will show a dialog box. Note: This is not compiled in console mode or with {$APPTYPE CONSOLE} as a parm. Idealistically, this should allow a multi-format app, if desired.
(It should go without saying from looking at the source, but the API function used works in Windows XP or above)
Code:
program writecon; uses windows, dialogs, sysutils;
type
AConsoleFunc = function(dwProcessId: Longint): boolean; stdcall;
var
AttachConsole: AConsoleFunc;
Handle: THandle;
procedure dlg_error(instr: string);
begin
MessageDlg(instr, mtInformation, [mbOk], 0);
halt(1);
end;
function load_attach_console: boolean;
{ attach console. Dynamically load KERNEL32.DLL to protect us
from a linkage error if we aren't running on Windows XP for the
AttachConsole function }
var
retvalue: Boolean;
begin
retvalue := false;
Handle := LoadLibrary('KERNEL32.DLL');
if Handle <> 0 then
begin
@AttachConsole := GetProcAddress(Handle, 'AttachConsole');
if @AttachConsole <> nil then
begin
if AttachConsole(-1) then
retvalue := true;
end;
FreeLibrary(Handle);
end;
load_attach_console := retvalue;
end;
function windows_version: boolean;
{ returns true if Windows XP, false if anything lower }
var
OsVersion: TOsVersionInfo;
retvalue: boolean;
begin
OsVersion.dwOsVersionInfoSize := sizeof(OsVersion);
retvalue := false;
if GetVersionEx(OsVersion) then
begin
if OsVersion.dwPlatformId = VER_PLATFORM_WIN32_NT then
begin
if (OsVersion.dwMajorVersion > 5) then
retvalue := true
else
if (OsVersion.dwMajorVersion = 5) and
(OsVersion.dwMinorVersion > 0) then
retvalue := true;
end;
end;
windows_version := retvalue;
end;
begin
if windows_version = false then
dlg_error('You need to run Windows XP or above for this.');
if load_attach_console = true then
begin
writeln;
writeln('This is running in the console.');
write('Press ENTER to continue.');readln;
FreeConsole;
end
else
dlg_error('This is not running in the console.');
end.