I've been trying to write to a console created with AllocConsole() in my C#
GUI app, and everything seems to work ok, except for the fact that nothing I
write actually shows up in the console. I was hoping perhaps someone could
point me to an example of how to use the console from the GUI, or perhaps
tell me what I'm doing wrong:
[DllImport("Kernel32.dll")] public static extern bool AllocConsole();
[DllImport("Kernel32.dll")] public static extern bool FreeConsole();
[DllImport("Kernel32.dll")] public static extern bool SetConsoleTitle(
string ConsoleTitle );
[DllImport("Kernel32.dll")] public static extern bool
SetConsoleTextAttribute( int hConsoleOutput, short wAttributes );
[DllImport("Kernel32.dll")] public static extern bool WriteFile( int hFile,
string lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten,
int lpOverlapped);
[DllImport("Kernel32.dll")] public static extern int GetStdHandle( int
nStdHandle );
[DllImport("Kernel32.dll")] public static extern bool
SetConsoleActiveScreenBuffer( int hConsoleOutput );
const int STD_INPUT_HANDLE = -10;
const int STD_OUTPUT_HANDLE = -11;
const int STD_ERROR_HANDLE = -12;
// Here's the code that attempts to write to the console, note that none of
the exceptions are thrown, it's just that nothing happens.
private void Form1_Load(object sender, System.EventArgs e)
{
// Allocate a console
AllocConsole();
SetConsoleTitle( "Test Title" );
int output = 0;
int hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if( hStdout == -1 )
throw new Exception("Stdout bad");
if( !WriteFile( hStdout, "1234\n", 5, ref output, 0) )
{
throw new Exception("Write File Failed");
}
}
I don't know the URL but a quick search on MSDN should turn
it up. It has a good example too.
-c
"Nick Shaffner" <ni...@wxp3d.com> wrote in message
news:u5xulCJHCHA.2772@tkmsftngp12...
As an interesting aside, I've managed to get it working using
int hStdout = CreateFile("CONOUT$",
GENERIC_READ | GENERIC_WRITE, // access mode
FILE_SHARE_READ | FILE_SHARE_WRITE,//int dwShareMode, // share mode
0, // SD
OPEN_EXISTING, // how to create
0, // file attributes
0 // handle to template file
);
(with CreateFile imported of course), but I get a file not found doing:
FileStream ConOut = File.Open( "CONOUT$", FileMode.Open,
FileAccess.ReadWrite, FileShare.ReadWrite);
I'd still like to figure out how to set up the console without using
CreateFile if possible, however.
Nick
> As an interesting aside, I've managed to get it working using
>
> int hStdout = CreateFile("CONOUT$",
> I'd still like to figure out how to set up the console without using
> CreateFile if possible, however.
I'd like to know the same thing - did you ever get anywhere with this?
Works like a champ ... I've attached a rewritten form, that's a bit
easier to plug into arbitrary apps.
--
My Kylix book http://www.midnightbeach.com/kylix
Consulting & contract programming http://www.midnightbeach.com
Stale homeschool resources http://www.midnightbeach.com/hs