Can not Start an executable from C++ - c++

Python can start an executable file but not C++.
Python -
os.system('cmd /c "start FlaskServer.exe"')
C++ - (I tried 4 different versions)
system("cmd /c \"start FlaskServer.exe\"");
system("start FlaskServer.exe");
ShellExecute(0, L"open", L"cmd", L"/c \"start FlaskServer.exe\"", 0, 0);
ShellExecute(0, L"open", L"FlaskServer.exe", 0, 0, 0);
Note - The file I am trying to execute is a no GUI no console app(flask server) coded in python. It had no GUI I compiled it as GUI to avoid console. In python, it gets opened as a background process but in c++, not listed in the tasklist. Although, other programs with GUI are running fine.

The problem was that being new to c++, I did not knew how to use Win32 buttons. I created WM_command with 2 button events, one for starting the application and other for killing it. I did not put "return 0" at the end. So, it first executed and the killed by the application.

Related

Terminating Process in Windows 10 OS

Background Information: I'm developing an Windows 10 app. Within my app, some outputs are displayed onto a window console requiring a new process.
Code Snippet:
PROCESS_INFORMATION pi;
STARTUPINFO si;
// CreateProcess is defined in processthreadsapi.h
BOOL newProcess = CreateProcess (
0, pszCmdLine, 0, 0, FALSE, DEBUG_THIS_ONLY_PROCESS, 0, 0, &si, &pi
);
In the above code snippet, pszCmdLine can be "cmd.exe /c dir", "cmd.exe /c ipconfig", or essentially any Windows terminal cmd.
Problem: On the front end, a new cmd console is generated and the user is able to terminate it. However, it's kept alive in the background. I've attached snips below:
Before Process Accumulating:
In the above snip, it shows "cmd.exe /c dir" being executed and outputted into a cmd console.
After Processes Accumulates:
In the above snip, it shows how I launched the same cmd 4 times and closed it 3 times (i.e. the counter is "(4)" including the main process).
Real World Problem: This is essentially consuming memory and has the ability to degrade performance.
Initial Curiosity: Shouldn't the Windows OS handle the killing of this process when the user clicks the "x"?
Has anyone faced a similar issue before?
Solution:
Change DEBUG_ONLY_THIS_PROCESS to 0 or CREATE_NEW_CONSOLE.
My Thoughts:
I suppose the idea behind DEBUG_ONLY_THIS_PROCESS is to leave the window handle open for the user to observe the output whereas CREATE_NEW_CONSOLE allocates and frees the memory as needed.

QProcess doesn't show the command window

I have the following code which runs an exectuable using QProcess. The code all runs fine and the new executable runs and is all fine.
QString fileName = ui.textBrowser_csvFile->toPlainText();
QString tableName = ui.textBrowser_2->toPlainText();
QString program = "resources/myExe.exe";
QStringList arguments;
arguments << tableName << fileName;
bool res = QProcess::startDetached(program, arguments);
It is a Qt Console Application using QCoreApplication and there it doesn't spawn the terminal window like it would if I run it normally. It would be useful to monitor the progress of the executable so how do I get my Application to run the new program and display the terminal window?
Edit Possible duplicate does technically answer the question, but I have answered this question with a working solution.
So as discussed in the comments on my questions this StackOverflow post explains that this is infact correct behaviour when using the startDetached() function.
I'm not entirely sure what the answer to that question was suggesting to do but here is my working solution.
system() is a windows specific function which "can execute any command that can run on terminal if operating system allows" link
If I replace this line:
bool res = QProcess::startDetached(program, arguments);
with the following, then it works:
system(QString("D:\\Qt\\5.9.1\\msvc2017_64\\bin\\myApp.exe " +tableName +" " + fileName).toStdString().c_str());
In the short term I have simply moved this application into the Qt folder because it needs the DLLs however with a proper release of this app you can run it from wherever, including from next to the application that is running it.
I do then get a terminal window and my app runns correctly.
When migrating from Qt 5.7.0.0(x86) to 5.10.0.0(x64) I was really surprised to see that using the new Qt version, a child (launched with "QProcess::startDetached") process will not show up it's console (even though it's a console application! (SubSystem:CONSOLE))
MS documentation regarding "AllocConsole" says:
Console applications are initialized with a console, unless they are
created as detached processes (by calling the CreateProcess function
with the DETACHED_PROCESS flag).
https://learn.microsoft.com/en-us/windows/console/allocconsole
Console processes are not attached to a console if they are created
using CreateProcess with DETACHED_PROCESS
https://learn.microsoft.com/en-us/windows/console/creation-of-a-console
So I'm assuming that new Qt versions are using the "CreateProcess" with the "DETACHED_PROCESS" flag.
What I've ended up doing:
For child process I'm now using "SubSystem:WINDOWS". (Really
important)
Inside the child process I'm creating the new console by using "AllocConsole()"
Using: "freopen("CONOUT$", "w", stderr);" and "freopen("CONOUT$",
"w", stdout);" ("stderr" is really important if you want to capture qDebug, qInfo, etc...)
P.s.
If you would need to use "SubSystem:CONSOLE", be sure to call "FreeConsole" before calling "AllocConsole". This is required, because child process will by default be using parent process console...

Working on Win32 App, would like output to both Win32 window and console window

I have looked fairly thoroughly through posts on this and other sites and it seems like most of the answers were from a number of years ago. I'm looking to create a Win32 C++ app that uses OpenGL functionality. Previously I have debugged these programs by porting the significant C++ code functions to a Win32 Console App. At this point I need to be able to debug through output to console window while interacting with the GLUT window. So, what I am looking for is a way to produce two windows from Win32 main - one holding the GLUT functionality (normal Win32), and one holding console output (not native to the Win32 project app). Is this even possible? If not, can someone suggest a link for debugging interactive GLUT programs?
Matt S.
You can add a console to a GUI programme by hijacking the parent's process console or allocating a new one:
if (! AttachConsole(ATTACH_PARENT_PROCESS)) // try to hijack existing console of command line
AllocConsole(); // or create your own.
DWORD nw,nr; // demo with windows native console i/o
char buff[32];
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), L"Hello Matthew !", 15, &nw, NULL);
This works fine if you do not foresee input on the console.
If you prefer to use stream output instead of native windows console functions, you 'd be interested in this SO question

Windows C++ CMD window switching

Hello fellow programmers, I have a problem with some console applications in a C++ program, and my objective is as follows.
Create first CMD window.
Execute a command. (system("print some error text");)
Create second CMD window.
Change system(...) focus to second CMD window.
Execute a command.
Change system(...) focus to first CMD window.
Execute a command.
The end goal of all this is to create a function that will be executed by a CMD application that will spawn another CMD window, execute a command on it, and then return focus to the original CMD window to continue executing other code. I do not need to keep track of the window, or be able to return to it. Just create new window, switch focus to it, execute a command, return focus to original window.
The first CMD window is created when the application is started.
Executing a command to this window with system(...); works fine.
I create a second CMD window with
HWND new_hWnd = NULL;
ShellExecute(new_hWnd, "open", "cmd.exe", NULL, NULL, SW_SHOW);
This is where I have problems, I have not been able to redirect system(...) to a different CMD window, and this is the part I need help with because if I can figure this out, then steps 5, 6 and 7 will be easy to complete.
I've tried researching this online and have come across some different examples using "pipes" but have not been able to recreate them, or understand them. Also, I noticed there is a
GetConsoleWindow();
function that returns a handle to the current CMD window, which to me kinda signals that there should be a way to switch between CMD windows by using handles, but since I have not switched focus to the other CMD window I can not call that function to get it's handle.
So, how do I make system(...) target different CMD windows with handles? If that is not possible, how can I implement this "pipe" system.
If the solution is the latter, please try to be as detailed and simple as possible with it because every example of it I have found online is really large and hard to read/understand.
If there is no easy way to implement "pipes" then please post or point me to the best(something that will help me understand how pipes work) example you can find and I will keep working with it till I figure it out. Thank you in advance!
You can create a new console for the new process by specifying the dwCreationFlags value CREATE_NEW_CONSOLE when calling CreateProcess.
See the documentation:
Process Creation Flags: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
CreateProcess function: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

How can I hide the command prompt of an application after it has started?

How do I go about suppressing the command prompt of a c++ application using the mingw compiler AFTER the program has started.. -mwindows works great in the linker settings but I want to be able to toggle it whilst the program is running, is this possible at all?
I am using a text editor and command line so no IDE related answers please.
As far as I know: no, at least not with a single executable. When you open an application in a Windows based console, it will start an instance of conhost.exe in order to provide an environment to your command line application. The console host will run as long as your applications hasn't exited.
It's hard to determine in which circumstances you'll need this behavior. But you could create two application - one which is a simple command line application, and one which has been compiled with -mwindows. The latter could call the first. After the first has exited the second will continue executing.
Note that this will leave the user bewildered, as it seems to him your application has stopped (as the console window has been closed) and a -mwindow compiled application doesn't create any GUI elements.
You can use WinAPI function ShowWindow to hide and show any window. There is a quirk, however - this function accepts an HWND handle as its argument and there is no obviuos way to obtain console HWND. Following is pretty convoluted way to get it:
HWND GetConsoleHwnd(void)
{
#define MY_BUFSIZE 1024 // Buffer size for console window titles.
HWND hwndFound; // This is what is returned to the caller.
TCHAR pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated
// WindowTitle.
TCHAR pszOldWindowTitle[MY_BUFSIZE]; // Contains original
// WindowTitle.
// Fetch current window title.
GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
// Format a "unique" NewWindowTitle.
TCHAR * format=_TEXT("%d/%d");
wsprintf(pszNewWindowTitle,format,
GetTickCount(),
GetCurrentProcessId());
// Change current window title.
SetConsoleTitle(pszNewWindowTitle);
// Ensure window title has been updated.
Sleep(40);
// Look for NewWindowTitle.
hwndFound=FindWindow(NULL, pszNewWindowTitle);
// Restore original window title.
SetConsoleTitle(pszOldWindowTitle);
return(hwndFound);
}
Forgive me for this dirty trick, but it works perfectly in my code and is an official way of getting console HWND.
Some programs have to be of a console type. Like Emacs where the same executable can be launched to operate in console (with -nw option) and in GUI.
To hide that console there are lots of methods (including esoteric WSH scripts, or 3rd party utils, like nircmd exec hide notepad.exe) but there is a simple modern portable way:
powershell -c Start-Process -WindowStyle Hidden -FilePath notepad.exe
You can wrap that ugly command into .bat script alias.
PS Use Task Manager to kill hidden Notepad ))