473,599 Members | 3,139 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 RedirectIOToCon sole(DWORD dwParent)
{
int hConHandle;
long lStdHandle;
FILE *fp;

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

// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHan dle(STD_OUTPUT_ HANDLE);
hConHandle = _open_osfhandle (lStdHandle, _O_TEXT);
fp = _fdopen(hConHan dle, "w");

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

// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHan dle(STD_INPUT_H ANDLE);
hConHandle = _open_osfhandle (lStdHandle, _O_TEXT);
fp = _fdopen(hConHan dle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);

// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHan dle(STD_ERROR_H ANDLE);
hConHandle = _open_osfhandle (lStdHandle, _O_TEXT);
fp = _fdopen(hConHan dle, "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(HINST ANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PA RAMETER(hPrevIn stance);
UNREFERENCED_PA RAMETER(lpCmdLi ne);

// TODO: Place code here.
HANDLE hSnapshot = CreateToolhelp3 2Snapshot(TH32C S_SNAPPROCESS, 0
);
wchar_t buffer[2000+1] = { '\0' };
DWORD dwCallingProces sID = 0UL;
if (hSnapshot != (HANDLE)-1)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First (hSnapshot, &pe))
{
DWORD MyPID = GetCurrentProce ssId();
do
{
if (pe.th32Process ID == MyPID)
{
dwCallingProces sID = pe.th32ParentPr ocessID;

if (RedirectIOToCo nsole
(pe.th32ParentP rocessID))
{
//cerr << "Failed";
for (int i = 0;i < 10;i++)
printf("Outputt ing Line %d\n",i+1);

}
else
{
MessageBox(NULL ,L"Failed",L"At taching
Console",MB_ICO NERROR);
}
}
} while (Process32Next( hSnapshot, &pe ));
}
CloseHandle(hSn apshot);
}
return 0;//Other code snipped for brevity
}
Jun 20 '07 #1
4 10499
"Peter Nimmo" <Pe********@new sgroups.nospamw rote 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********@new sgroups.nospamw rote 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 RedirectIOToCon sole(DWORD dwParent)
{
int hConHandle;
long lStdHandle;
FILE *fp;

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

// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHan dle(STD_OUTPUT_ HANDLE);
hConHandle = _open_osfhandle (lStdHandle, _O_TEXT);
fp = _fdopen(hConHan dle, "w");

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

// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHan dle(STD_INPUT_H ANDLE);
hConHandle = _open_osfhandle (lStdHandle, _O_TEXT);
fp = _fdopen(hConHan dle, "r");
*stdin = *fp;
setvbuf(stdin, NULL, _IONBF, 0);

// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHan dle(STD_ERROR_H ANDLE);
hConHandle = _open_osfhandle (lStdHandle, _O_TEXT);
fp = _fdopen(hConHan dle, "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(HINST ANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PA RAMETER(hPrevIn stance);
UNREFERENCED_PA RAMETER(lpCmdLi ne);

// TODO: Place code here.
HANDLE hSnapshot = CreateToolhelp3 2Snapshot(TH32C S_SNAPPROCESS, 0
);
wchar_t buffer[2000+1] = { '\0' };
DWORD dwCallingProces sID = 0UL;
if (hSnapshot != (HANDLE)-1)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First (hSnapshot, &pe))
{
DWORD MyPID = GetCurrentProce ssId();
do
{
if (pe.th32Process ID == MyPID)
{
dwCallingProces sID = pe.th32ParentPr ocessID;

if (RedirectIOToCo nsole
(pe.th32ParentP rocessID))
{
//cerr << "Failed";
for (int i = 0;i < 10;i++)
printf("Outputt ing Line %d\n",i+1);

}
else
{
MessageBox(NULL ,L"Failed",L"At taching
Console",MB_ICO NERROR);
}
}
} while (Process32Next( hSnapshot, &pe ));
}
CloseHandle(hSn apshot);
}
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 ¡°asynchronousl y¡±.

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.c om and
the GUI MyApplication.e xe. Cmd.exe will launch the .com file first, the
shell will launch the .exe first and everybody is happy:
MyApplication.e xe ¨C This is a Windows Application, and performs no output
to the console.
MyApplication.c om ¨C This is a Console Application, it calls
MyApplication.e xe 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\d evenv /?
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\d evenv.com /?
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\d evenv.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
105788
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: System.out.print((char)27 + "[2J");
9
10965
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 console title is easily set with the DOS-command 'title NewTitle'. But I'd like to do this from a Python script. os.system('title NewTitle') will not do, because it spawns a new process.
5
8713
by: Pengyu | last post by:
Hi, How to add a console window to a Windows application? Thank you very much in advance, Pengyu
6
3228
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 I have all the code set up to do this, however when I issue a Console.WriteLine instruction, nothing gets written to the console. In fact, the command prompt comes back before the program has finished executing. What do I need to do?
8
4755
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 which a win32 is not. You may correct me if I'm wrong on this point. //Tony
8
3684
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 & "\MameGames.cfg", AppWinStyle.NormalFocus, True) The problem is that the parameter Application.StartupPath has spaces (C:\Program Files, for instance) and won't execute from a command prompt without being incased in quotes. I can't figure out the...
1
2326
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 in the command prompt(I recently found out that it is called a console application.....more explanation will be appreciated and helpful)........
2
2742
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 page), nothing happens - i.e. no information is printed on the console, and the setup application simply quits with no warning/error message. has anyone managed to succesfully install SciPy using scipy-0.6.0.win32-py2.5.exe & ActiveState Python on...
7
9352
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 display the Windows form. The form is being displayed but the command only returns when the form is closed. I want the command line to return immediately, leaving the form displayed.
0
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7916
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8401
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8404
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8053
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8268
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3900
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
1252
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.