473,406 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

WIN32 Windows Application Outputting to Command Prompt as if a Console Program - How?

Hi,

I am writting a windows application that I want to be able to act as if
it where a Console application in certain circumstances, such as error
logging.

Whilst I have nearly got it, it doesn't seem to write to the screen in
the way I would expect.

The output is:

C:\>Test.exe

C:\>Outputting Line 1
Outputting Line 2
Outputting Line 3
Outputting Line 4
Outputting Line 5
Outputting Line 6
Outputting Line 7
Outputting Line 8
Outputting Line 9
Outputting Line 10

Instead of:

C:\>Test.exe
Outputting Line 1
Outputting Line 2
Outputting Line 3
Outputting Line 4
Outputting Line 5
Outputting Line 6
Outputting Line 7
Outputting Line 8
Outputting Line 9
Outputting Line 10

C:\>

Code is as follows:

#include <Tlhelp32.h>
#include <cstdio>
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <ios>

BOOL RedirectIOToConsole(DWORD dwParent)
{
int hConHandle;
long lStdHandle;
FILE *fp;

// allocate a console for this app
BOOL bRet = AttachConsole(dwParent);
if (!bRet)
return bRet;

// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");

*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);

// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);

// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stderr = *fp;
setvbuf(stderr, NULL, _IONBF, 0);

// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
ios::sync_with_stdio();
return bRet;
}

int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0
);
wchar_t buffer[2000+1] = { '\0' };
DWORD dwCallingProcessID = 0UL;
if (hSnapshot != (HANDLE)-1)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First(hSnapshot, &pe))
{
DWORD MyPID = GetCurrentProcessId();
do
{
if (pe.th32ProcessID == MyPID)
{
dwCallingProcessID = pe.th32ParentProcessID;

if (RedirectIOToConsole
(pe.th32ParentProcessID))
{
//cerr << "Failed";
for (int i = 0;i < 10;i++)
printf("Outputting Line %d\n",i+1);

}
else
{
MessageBox(NULL,L"Failed",L"Attaching
Console",MB_ICONERROR);
}
}
} while (Process32Next( hSnapshot, &pe ));
}
CloseHandle(hSnapshot);
}
return 0;//Other code snipped for brevity
}
Jun 20 '07 #1
4 10466
"Peter Nimmo" <Pe********@newsgroups.nospamwrote in message
news:Xn**********************************@127.0.0. 1...
I am writting a windows application that I want to be able to act as if
Whilst I have nearly got it, it doesn't seem to write to the screen in
the way I would expect.

The output is:

C:\>Test.exe

C:\>Outputting Line 1
Outputting Line 2
...
Outputting Line 10

Instead of:

C:\>Test.exe
Outputting Line 1
Outputting Line 2
...
Outputting Line 10
Write a carriage return / line feed pair ( "\r\n") before the first line.

Regards,
Will
www.ivrforneginners.com

Regards,
Will
Jun 20 '07 #2

"Peter Nimmo" <Pe********@newsgroups.nospamwrote in message
news:Xn**********************************@127.0.0. 1...
Hi,

I am writting a windows application that I want to be able to act as if
it where a Console application in certain circumstances, such as error
logging.

Whilst I have nearly got it, it doesn't seem to write to the screen in
the way I would expect.

The output is:

C:\>Test.exe

C:\>Outputting Line 1
Outputting Line 2
Outputting Line 3
Outputting Line 4
Outputting Line 5
Outputting Line 6
Outputting Line 7
Outputting Line 8
Outputting Line 9
Outputting Line 10

Instead of:

C:\>Test.exe
Outputting Line 1
Outputting Line 2
Outputting Line 3
Outputting Line 4
Outputting Line 5
Outputting Line 6
Outputting Line 7
Outputting Line 8
Outputting Line 9
Outputting Line 10

C:\>
The command prompt waits for a console application to finish, but not for a
windows application (I think this behavior is new in XP, I definitely
remember having to do "start notepad" if I wanted to keep using my command
prompt).
>
Code is as follows:

#include <Tlhelp32.h>
#include <cstdio>
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <ios>

BOOL RedirectIOToConsole(DWORD dwParent)
{
int hConHandle;
long lStdHandle;
FILE *fp;

// allocate a console for this app
BOOL bRet = AttachConsole(dwParent);
if (!bRet)
return bRet;

// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");

*stdout = *fp;
setvbuf(stdout, NULL, _IONBF, 0);

// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);

// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen(hConHandle, "w");
*stderr = *fp;
setvbuf(stderr, NULL, _IONBF, 0);

// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
ios::sync_with_stdio();
return bRet;
}

int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);

// TODO: Place code here.
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0
);
wchar_t buffer[2000+1] = { '\0' };
DWORD dwCallingProcessID = 0UL;
if (hSnapshot != (HANDLE)-1)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First(hSnapshot, &pe))
{
DWORD MyPID = GetCurrentProcessId();
do
{
if (pe.th32ProcessID == MyPID)
{
dwCallingProcessID = pe.th32ParentProcessID;

if (RedirectIOToConsole
(pe.th32ParentProcessID))
{
//cerr << "Failed";
for (int i = 0;i < 10;i++)
printf("Outputting Line %d\n",i+1);

}
else
{
MessageBox(NULL,L"Failed",L"Attaching
Console",MB_ICONERROR);
}
}
} while (Process32Next( hSnapshot, &pe ));
}
CloseHandle(hSnapshot);
}
return 0;//Other code snipped for brevity
}
Jun 21 '07 #3
Hi Peter,

Yes, I can reproduce out this behavior.

Normally, "console" applications (ones that begin with main/wmain) are
executed by cmd ¡°synchronously¡±, while ¡°windows¡± applications (ones
that begin with WinMain/wWinMain) are executed ¡°asynchronously¡±.

This is independent of whether said application writes to any consoles or
not.

So, your test program is a ¡°windows¡± app, so cmd.exe starts it up and
then immediately returns control to the user (printing a prompt for the
next command). The user can even use that prompt before test does
anything. (Put in a sleep statement in test.exe to observe this.) That¡¯s
because most ¡°windows¡± program launch a new GUI window and interact with
the user that way.

When your app now prints to the console, it just prints wherever the cursor
is (which means it starts at the end of the command prompt, and also those
messages would be intermixed with any commands the user types and any
results from those other commands), and when it gets done printing, cmd.exe
doesn¡¯t know that the appearance of its prompt has been trashed and needs
to be reprinted. [And if you were halfway through typing that command,
that command fragment is still there to be continued, even though you¡¯ve
spewed a whole bunch of stuff to the console.]

Now, the standard way to deal with this is:
1. Use a console app. Note that the cmd.exe prompt won¡¯t be available
again until your program exits.
2. Use a separate console instead of the one that launched your program.
3. Use windows GUI to show error messages.
4. Use a hybrid approach if this makes sense ¨C a small console app that
parses the cmd line and if it decides it wants to act like a console app,
it prints those messages, but otherwise spawns a GUI app (and exits) to
return the cmd prompt to the user. The GUI app then communicates to the
user via GUI windows, etc.

Regarding #4, if you do this, name the console app MyApplication.com and
the GUI MyApplication.exe. Cmd.exe will launch the .com file first, the
shell will launch the .exe first and everybody is happy:
MyApplication.exe ¨C This is a Windows Application, and performs no output
to the console.
MyApplication.com ¨C This is a Console Application, it calls
MyApplication.exe and returns output from the Windows Application to the
console via some kind of IPC.

See devenv.com/devenv.exe in Visual Studio as an example:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv /?
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv.com /?
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv.exe /?

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 22 '07 #4
Additionally, if you are interested in option #4, you may read the 2 links
below for details:
http://msdn.microsoft.com/msdnmag/issues/04/02/CQA/
http://blogs.msdn.com/junfeng/archiv.../06/68531.aspx

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Jun 22 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
by: Dave | last post by:
Hi, I have done some research, trying to Clear The Screen in java code. The first option was the obv: system.out.print("\n\n\n\n\n\n\n\n\n\n\n\n"); then i heard about this method:...
9
by: runes | last post by:
Hi, I'm trying to set the title of the console window (CMD.EXE) in Windows. I want it set to the basename of the current directory and it should stay after the script has finished. Now, the...
5
by: Pengyu | last post by:
Hi, How to add a console window to a Windows application? Thank you very much in advance, Pengyu
6
by: Mark Allison | last post by:
Hi, I have an application that I want to be to run in Console mode and GUI mode. If no params are entered, I want the GUI fired up, if params are entered, then go into console mode. I believe...
8
by: Tony Johansson | last post by:
Hello! I just wonder what the difference is between a native win32-app and MFC. What I know is that you can use Win32 API in both cases. I think an MFC application is connected with a GUI...
8
by: jcrouse | last post by:
I am trying to run a command from a command prompt using the shell command. Here is the syntax I want to execute: Shell(lblMameExePath.Text & " -listinfo >" & Application.StartupPath &...
1
by: MNA | last post by:
Here are some of my querries..... what is command prompt in windows XP? I am learning C programming and using Turbo C Compiler.......Now, I want to make a text editor which I can open...
2
by: Frank Moyles | last post by:
Hi, I want to use SciPy library. I am using W2k, and ActiveState Python 2.5. I have succesfully numpy, but when I run the scipy-0.6.0.win32-py2.5.exe (from the downloads section on the SciPy...
7
by: Jwe | last post by:
Hi, I've written a program which has both a command line interface and Windows form interface, however it isn't quite working correctly. When run from command line with no arguments it should...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.