Using Windows, I entered a command in my cmd window to run an executable file that has your basic "Hello, world!" line printed by the program. When I enter the "start out.exe" command though, a window opens and closes in a quick second. I'm guessing that this window is the window where the hello world message is being printed, but it closes so quickly (maybe because the program is finished). Is there some sort of setting I have that is causing the window to close immediately? Is that just the default? And if so, is there a setting or something that I can change to prevent the window from closing immediately (without changing the nature of the program)? Thanks in advance for your help. I've seen some similar questions, but the ones I have seen are specifically for Linux/Unix or suggested to change the program itself.
If you possess .PDB files, generated at build time (symbols of .EXE file) and required .DLL libraries for your program (In your case those might not be required due to the simple nature of a "Hello World" program), you could try to open the executable as project in Visual Studio and attach a debugger to it, using breakpoints to stop program executions before main returns. This article shows how to do it as a proof of concept.
Open .EXE file by opening VS and navigating to File-Open-Project/Solution and selecting the executable file, then right-click on your "solution" and press Debug-Start new instance. PDB and DLL files should be in the same folder as EXE file.
If you also don't have source code available of the program, follow this advice in order to try to debug it:
To effectively debug you’ll also need the source code that was used to build the EXE, even for just a few files that you care about. You’ll need to locate those files and open them in Visual Studio. If the source code isn’t the exact same as the source code that was built the EXE Visual Studio will warn you when you try to insert a breakpoint and the breakpoint won’t bind. That behavior can be overridden from the Breakpoint Settings peek window. In the settings peek window click on the Must match source link text and then check the box to allow mismatched source, as illustrated below. Of course, with mismatched source you never really know what’s going to happen, so use at your peril.
Disclaimer: I'm not really sure how this method is effective without source files, but I think it's the closest to your answer without changing the actual program.
As another option, you can try invoking your executable file by creating a custom program that invokes the program and redirects its stdout and stderr, like this, for example, or using pipes, check there. The custom program would eventually create a process using as executable your original .exe program and do something with stdout/stderr, for example showing them in your custom program console or saving the output to a file, thus allowing you to read your original program output without the window closing issue (Of course, the original window will still close itself, but I don't think it would matter for you too much).
Or if you want a quick'n'dirty way, you could try to capture the program output by making an invoker Java program. Replace commands array with your program executable name with arguments:
Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(proc.getErrorStream()));
// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
Related
How do I create a windows application that does the following:
it's a regular GUI app when invoked with no command line arguments
specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate
it must be a single executable. No cheating by making a console app exec a 2nd executable.
assume the main application code is written in C/C++
bonus points if no GUI window is created when "--help" is specified. (i.e., no flicker from a short-lived window)
In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell.
Microsoft designed console and GUI apps to be mutually exclusive.
This bit of short-sightedness means that there is no perfect solution.
The most popular approach is to have two executables (eg. cscript / wscript,
java / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this "cheating".
You've got two options - to make a "console executable" or a "gui executable",
and then use code to try to provide the other behaviour.
GUI executable:
cmd.exe will assume that your program does no console I/O so won't wait for it to terminate
before continuing, which in interactive mode (ie not a batch) means displaying the next ("C:\>") prompt
and reading from the keyboard. So even if you use AttachConsole your output will be mixed
with cmd's output, and the situation gets worse if you try to do input. This is basically a non-starter.
Console executable:
Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems.
The first is that if you run it from the command line with no arguments (so you want the GUI),
cmd will still wait for it to terminate before continuing, so that particular
console will be unusable for the duration. This can be overcome by launching
a second process of the same executable (do you consider this cheating?),
passing the DETACHED_PROCESS flag to CreateProcess() and immediately exiting.
The new process can then detect that it has no console and display the GUI.
Here's C code to illustrate this approach:
#include <stdio.h>
#include <windows.h>
int main(int argc, char *argv[])
{
if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process
{
MessageBox(0, "Hello GUI world!", "", 0);
}
else if (argc > 1) // we have command line args
{
printf("Hello console world!\n");
}
else // no command line args but a console - launch child process
{
DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS;
STARTUPINFO startinfo;
PROCESS_INFORMATION procinfo;
ZeroMemory(&startinfo, sizeof(startinfo));
startinfo.cb = sizeof(startinfo);
if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo))
MessageBox(0, "CreateProcess() failed :(", "", 0);
}
exit(0);
}
I compiled it with cygwin's gcc - YMMV with MSVC.
The second problem is that when run from Explorer, your program will for a split second
display a console window. There's no programmatic way around this because the console is
created by Windows when the app is launched, before it starts executing. The only thing you can
do is, in your installer, make the shortcut to your program with a "show command" of
SW_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFO
in your program, so don't do that.
I've tested this by hacking cygwin's "mkshortcut.exe". How you accomplish
it in your install program of choice is up to you.
The user can still of course run your program by finding the executable in Explorer and
double-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it.
You can use AllocConsole() WinApi function to allocate a console for GUI application. You can also try attaching to a console of a parent process with AttachConsole(), this makes sense if it already has one. The complete code with redirecting stdout and stderr to this console will be like this:
if(AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
}
I found this approach in the Pidgin sources (see WinMain() in pidgin/win32/winpidgin.c)
I know my answer is coming in late, but I think the preferred technique for the situation here is the ".com" and ".exe" method.
This may be considered "cheating" by your definition of two executables, but it requires very little change on the programmers part and can be done one and forgot about. Also this solution does not have the disadvantages of Hugh's solution where you have a console windows displayed for a split second.
In windows from the command line, if you run a program and don't specify an extension, the order of precedence in locating the executable will prefer a .com over a .exe.
Then you can use tricks to have that ".com" be a proxy for the stdin/stdout/stderr and launch the same-named .exe file. This give the behavior of allowing the program to preform in a command line mode when called form a console (potentially only when certain command line args are detected) while still being able to launch as a GUI application free of a console.
There are various articles describing this like "How to make an application as both GUI and Console application?" (see references in link below).
I hosted a project called dualsubsystem on google code that updates an old codeguru solution of this technique and provides the source code and working example binaries.
I hope that is helpful!
If I try to start debugging through the command "Open" of x64dbg, debugging stops without ever starting and a series of missing DLL errors are shown on the screen.
If I just open the program from WIN and THEN I use the attach command by selecting the process, debugging works.
Unfortunately I wanna "investigate" from the moment the program starts and not when it is already started.
How can I solve it ?
You need some anti-anti-debugging plugins (such as ScyllaHide) for x64dbg mentioned in this page to counter anti-debugging attempts and do some patching if needed:
https://github.com/x64dbg/x64dbg/wiki/Plugins
Operating Environment: Windows 7, Visual Studio 2010, CLR GUI.
So I've been given the unglorious task of enhancing a GUI application that is started from a command prompt. Because it is. Because poor design decisions by previous implementers. Anyway, it launches one of several GUIs depending upon the input arguments.
I'd like to be able to print back to the same command prompt window if (when) the user types something that the code doesn't understand.
Here's what I've tried (none of which output anything):
int main( array<System::String^>^ args )
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
OutputDebugString("hello");
Trace::WriteLine("hello");
Debug::Trace::WriteLine("hello");
Console::WriteLine("hello");
std::cout << "hello";
printf("hello");
return 0;
}
Thanks in advance!
Update: I don't want to use AllocConsole(), as that opens a new console that disappears along with all of the data when the application exits. Similarly, a pop-up message box won't work. I'm looking for a way to make the output persistent.
The only way I can get output from the application to date is via a message box (non-persistent) or opening a new console that disappears when the application exits (via AllocConsole() ). And I'm running from a command prompt, not the debugger's "Play" button.
Update
Why the down-vote for not doing research? I spent a day trying to solve this, looking through dozens of posts trying to find a solution, and to date I've found others looking for the same answer, but not finding it. AllocConsole() or changing the project type is always the solution, but neither is a solution for me.
Update
I added the "full code", which is the 2 statements. THAT IS ALL THE CODE. So simple. I'm skipping the start of the GUI because I don't care about that right now, I just want it to print back to the console where the application was started. The most basic HelloWorld. If there are project settings I need to post, I don't know which ones would be relevant. This is where I want to print to the console, before the GUI is ever up. I can't show the GUI if there is an error in the user input.
Right click on the project, select Properties
Under Linker -> System, Change Subsystem from Windows to Console.
A Windows subsystem application cannot write to console, but by changing the subsystem to Console (which can write to the calling console), the Form part of the application can still work (tested in Visual Studio 2010).
I want to be able to browse the source and set a debug point without having to hunt for a way to get the file open. I know you can open the original source and detach/reattach the debugger but that is a pain to do every time you run.
If you remember the name of the method you want to debug by heart, you can Add New Breakpoint (Ctrl+B) and type "MyClassName.MyMethodName" (enter). That will put a breakpoint in the beginning of that method, and when you run, as soon as it's hit, the file will open.
When developing a Win32 Application (non-console application) in Visual Studio 2005, is there any way to get the same sort of output as you do from the console?
For instance, say I want to see log statements (such as I would with cout in a console application) to trace the path my program has taken in the code.
My first thought would be that this could be done through the Output tab selecting something from its "Show output from:" dropdown, when debugging but I don't know what API I need to do this...
For example say I had the following in my windows application and wanted to know when the following function enters and exits writing the result to the Visual Studio window above.
void someFunction(void)
{
Win32APIConsoleLog("BEGIN: someFunction()");
// ...
Win32APIConsoleLog("END: someFunction()");
}
Is this possible? And if so, what what libraries do I need to include and what function calls do I need to make to write out to the console window?
OutputDebugString.
I assume that you want to write to the debug console, since that's what your screenshot shows. OutputDebugString is a nop when no debugger is attached, but it allows you to log whatever you want to the debugger's output.
OutputDebugStringW(L"This will go to the output.\n");
// or
OutputDebugString("This will go to the output.\n");