Author Topic: problems with SetConsoleActiveScreenBuffer  (Read 2192 times)

robert rozee

  • New Member
  • *
  • Posts: 43
problems with SetConsoleActiveScreenBuffer
« on: December 12, 2021, 04:16:32 pm »
    i'm still tinkering around with using the console from a GUI application, with some reasonable level of success. my latest problem, however, is in trying to persuade the windows console to display an alternate buffer, AND to have lazarus write to it. see the attached example project.

essentially, i can write to the console using writeln, but when i create an alternate buffer using CreateConsoleScreenBuffer and set it to default using SetConsoleActiveScreenBuffer, the output from writeln keeps going to the original buffer, not the alternate one.

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button2Click(Sender: TObject);        // attach to console and create new buffer
  2. var ScreenBuffer:HWND;
  3.               SA:SECURITY_ATTRIBUTES;
  4. begin
  5.   if IsConsole then ShowMessage('There is a Console already Attached') else
  6.   if AttachConsole(ATTACH_PARENT_PROCESS) then
  7.   begin
  8.     StdInputHandle:=0;
  9.     StdOutputHandle:=0;
  10.     StdErrorHandle:=0;
  11.     IsConsole:=True;                                   // in System unit
  12.     SysInitStdIO;                                      // in System unit
  13.     SetConsoleCtrlHandler(@ConsoleHandler, true);      // hook for ctrl-C, break, and close
  15.     SA.nLength:= sizeOf(SA);
  16.     SA.lpSecurityDescriptor := nil;
  17.     SA.bInheritHandle := false;
  19.     ScreenBuffer:= CreateConsoleScreenBuffer(GENERIC_READ or GENERIC_WRITE, 0, SA, CONSOLE_TEXTMODE_BUFFER, nil);
  20.     if ScreenBuffer=INVALID_HANDLE_VALUE  then ShowMessage('CreateConsoleScreenBuffer Failed');
  21.     if not SetConsoleActiveScreenBuffer(ScreenBuffer) then ShowMessage('SetConsoleActiveScreenBuffer Failed');
  22.     ID:='TWO '
  23.   end
  24. end;

in the attached example (lazarus 2.0.12, winXP), when LAUNCHED FROM A CONSOLE WINDOW, click on the 'attach1' button to attach back to the console using the original buffer, then click on 'test writeln' to see output successfully written to the console. now click 'detach'.

next, click on 'attach 2' - the console clears, suggesting that the alternate buffer has been activated - then click on 'test writeln' a few times. nothing is displayed. BUT, when you click on 'detach' the console switches back to the original buffer with the output from the pressing of 'test writeln' visible there.

i've been going round and round in circles with this, hopefully someone can provide some enlightenment. i do realize there are Win32 calls to write to the alternate buffer (WriteConsoleOutput, etc), but surely the plumbing behind writeln can be made to work?!

rob   :-)


TinyPortal © 2005-2018