CreateProcess Access Denied when invoked by sticky keys - c++

My program is designed to be a secure Sticky Keys hack. If sticky keys is invoked from logon, it will ask for a username and password to a local account. If they are correct, an instance of cmd.exe will be invoked as that user to avoid damage. When I double-click the sethc program from explorer,
It runs successfully.
When I run the same program with pressing shift five times,
It fails with error 5 Access Denied.
I can verify that sethc is run under winlogon when shift is pressed five times.
The whole file is:
// cmd.cpp : Defines the entry point for the console application.
//
#include <Windows.h>
#include <Lmcons.h>
#include <iostream>
#include <ctype.h>
#include <string>
#include <stdio.h>
#define winstring LPWSTR
#define stcas(x) static_cast<x>
#define INFO_BUFFER_SIZE 260
using namespace std;
void ReportError(LPCWSTR pszFunction, DWORD dwError = GetLastError())
{
wprintf(L"%s failed w/err 0x%08lx\n", pszFunction, dwError);
system("pause");
exit(dwError);
}
int main()
{
LPTSTR szCmdline[] = {"cmd"};
STARTUPINFOW si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
TCHAR un[UNLEN+1];
DWORD size = UNLEN + 1;
GetUserName(un, &size);
string una(un);
bool sys = !una.compare("SYSTEM");
if(!sys) {
system("cls");
if(!CreateProcessW(L"C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS | CREATE_BREAKAWAY_FROM_JOB, NULL, NULL, &si, &pi)) ReportError(L"normal Create process");
return 0;
}
wchar_t szUserName[INFO_BUFFER_SIZE] = {};
wchar_t szPassword[INFO_BUFFER_SIZE] = {};
wchar_t *pc = NULL;
HANDLE hToken = NULL;
HANDLE aToken = NULL;
BOOL dup = FALSE;
BOOL logon = FALSE;
printf("Enter the username: ");
fgetws(szUserName, ARRAYSIZE(szUserName), stdin);
pc = wcschr(szUserName, '\n');
if (pc != NULL) *pc = '\0'; // Remove the trailing L'\n'
cout << endl;
printf("Enter the password: ");
fgetws(szPassword, ARRAYSIZE(szPassword), stdin);
pc = wcschr(szPassword, '\n');
if (pc != NULL) *pc = '\0'; // Remove the trailing L'\n'
if(!LogonUserW(szUserName, NULL, szPassword, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &hToken)) ReportError(L"Logon");
else logon = TRUE;
if(!DuplicateTokenEx(hToken, TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL, SecurityImpersonation, TokenPrimary, &aToken)) ReportError(L"Impersonate");
else dup = TRUE;
if(!CreateProcessAsUserW(aToken,L"C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, FALSE, CREATE_BREAKAWAY_FROM_JOB, NULL, L"C:\\Windows\\System32\\", &si, &pi)){
ReportError(L"Create Process");
}
SecureZeroMemory(szPassword, sizeof(szPassword));
}
I would like to know why sethc is not allowed CreateProcess at all if it is derived from winlogon. I am running Windows 7. The weird thing is that system(command) works fine. I use system("pause"); once.

While it is difficult to say what your question actually is, be aware that there is a specific privilege called PROCESS_CREATE_PROCESS.
From MSDN:
PROCESS_CREATE_PROCESS (0x0080) Required to create a process.
A process lacking this privilege can't spawn child processes. system("pause"); does not create a child process, because pause is a built-in shell command, but I understand why you might have got that impression.
So check if your process has that privilege. Use process explorer or simply a WINAPI function, there's bound to be one.
If you want to know why Microsoft developers decided not to give that privilege to sethc, you'd have to ask them.

Related

Run command in c++ via CreateProcess and handle its input and output

I am trying to create a program in which you can execute commands. The output of these commands should be displayed in a GUI. For this I use QT (because I want to get familiar with WinAPI I don't use QProcess). In the current program it is already possible to redirect the output of a command with a handle. Now my question, how is it possible to interrupt the ReadFile if the command expects a user input.
As an example, I want to run the command yarn run from C++.
This returns as output that this command does not exist and asks which command I want to execute instead. At the moment the command aborts there (comparable with CTRL+C) and returns error No command specified. At this point, however, a user input should be possible.
Expected outcome of the program:
The output I get instead:
As you can see in picture 1 yarn asks the user for input. In image 2 there is no question at all. This behaviour is for example possible if you press CTRL+C if the question input shows up.
So how is it possible to make a user input in the gui (for now it would be enough to redirect the value of a variable into the input) and redirect it back to the process. The process should wait until it gets the input.
Command.h
#ifndef COMMAND_H
#define COMMAND_H
#include <string>
#include <cstdlib>
#include <cstdio>
#include <io.h>
#include <fcntl.h>
#include <stdexcept>
#include <windows.h>
#include <iostream>
#define BUFSIZE 256
class Project;
class Command
{
private:
int exitStatus;
const Project * project;
std::string cmd;
HANDLE g_hChildStd_IN_Rd = nullptr;
HANDLE g_hChildStd_IN_Wr = nullptr;
HANDLE g_hChildStd_OUT_Rd = nullptr;
HANDLE g_hChildStd_OUT_Wr = nullptr;
HANDLE g_hInputFile = nullptr;
void setupWindowsPipes();
void createWindowsError(const std::string &errorText);
void readFromPipe();
public:
Command() = delete;
explicit Command(std::string cmd, const Project *project);
void exec();
};
#endif // COMMAND_H
Command.cpp (the entry point which is called by the gui is exec())
#include "command.h"
#include "project.h"
Command::Command(std::string cmd, const Project *project) : exitStatus(0), project(project), cmd(std::move(cmd)) {}
void Command::createWindowsError(const std::string &errorText) {
DWORD code = GetLastError();
LPSTR lpMsgBuf;
if(code == 0) return;
auto size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0, NULL );
std::string msg(lpMsgBuf, size);
LocalFree(lpMsgBuf);
throw std::runtime_error(errorText + "()" + std::to_string(code) + ": " + msg);
}
void Command::setupWindowsPipes(){
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = true;
saAttr.lpSecurityDescriptor = nullptr;
if(!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0))
createWindowsError("StdOutRd CreatePipe");
if(!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
createWindowsError("StdOut SetHandleInformation");
if(!CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
createWindowsError("StdInRd CreatePipe");
if(!SetHandleInformation(g_hChildStd_IN_Rd, HANDLE_FLAG_INHERIT, 0))
createWindowsError("StdIn SetHandleInformation");
}
void Command::readFromPipe() {
DWORD dwRead;
char chBuf[BUFSIZE];
bool bSuccess = false;
for (;;)
{
dwRead = 0;
for(int i = 0;i<BUFSIZE;++i) {
chBuf[i] = '\0';
}
bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
if( ! bSuccess || dwRead <= 0 ) break;
std::cout << chBuf;
}
std::cout << std::endl;
}
void Command::exec() {
std::cout << "CMD to run: " << this->cmd << std::endl;
this->setupWindowsPipes();
STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdError = g_hChildStd_OUT_Wr;
si.hStdOutput = g_hChildStd_OUT_Wr;
si.hStdInput = g_hChildStd_IN_Rd;
si.dwFlags |= STARTF_USESTDHANDLES;
ZeroMemory(&pi, sizeof(pi));
char* dir = nullptr;
if(this->project != nullptr) {
auto n = this->project->getLocalUrl().size() + 1;
auto nString = this->project->getLocalUrl().replace("/", "\\");
dir = new char[n];
std::strncpy(dir, nString.toStdString().c_str(), n);
}
std::string cmdString = "cmd /c ";
cmdString.append(this->cmd);
char cmdCopy[cmdString.size() + 1];
cmdString.copy(cmdCopy, cmdString.size());
cmdCopy[cmdString.size() + 1] = '\0';
bool rc = CreateProcessA( nullptr,
cmdCopy,
nullptr,
nullptr,
true,
CREATE_NO_WINDOW,
nullptr,
dir,
&si,
&pi);
delete []dir;
if(!rc)
createWindowsError("Failed to create process");
std::cout << "PID: " << pi.dwProcessId << std::endl;
CloseHandle(g_hChildStd_OUT_Wr);
CloseHandle(g_hChildStd_IN_Rd);
readFromPipe();
std::cout << "fin reading pipe" << std::endl;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
It sounds like you have an XY problem, luckily you described X so we can address it.
The issue is not your failure to call WriteFile to store the response into the redirected input pipe. If the program were trying to read input, it would wait.
The issue is that the program is not requesting input at all. It has detected that interactive input is not possible, because it detects a pipe and assumes that a pipe is not interactive. So it doesn't perform the prompt or try to read from standard input at all. You can't provide an answer to a question that the program didn't ask!
(To confirm this is the behavior of the yarn program you are spawning, you can launch it from cmd.exe using a pipe to provide the input. cmd.exe has well-tested buffering logic for redirected input and output handles and you can be sure that any suspected deadlock in your code doesn't affect cmd.exe)
On Unix-like systems, this is solved by redirecting to a pseudo-tty (ptty) special file instead of a pipe special file, which causes the isatty() function to return true.
On Windows, this used to be effectively impossible, as the console API, implemented at kernel level, was permanently associated to the console subsystem csrss.exe which only exchanged data with the official Console Host process (owner of console windows).
Now however, Windows API supports pseudo-consoles. You can find a complete introduction on the Microsoft Dev Blog
Windows Command-Line: Introducing the Windows Pseudo Console (ConPTY)
The important function you need (in case that link breaks) is CreatePseudoConsole supported starting with Windows 10 version 1809 (October 2018 update).
When you use CreatePseudoConsole to promote the pipes and then supply this console to CreateProcess (instead of attaching pipes to your subprocess standard I/O streams), the subprocess will detect an interactive console, can use console API functions such as AttachConsole, can open the special filenames CONIN$ etc. And the data comes to you (and from you) instead of being linked to a console window.
There's also a complete sample on GitHub.
That same blog post also discusses the workaround used by "Terminal" and "remote shell" type software prior to the addition of CreatePseudoConsole in Windows 10, namely setting up the subprocess with a detached console, hiding the associated console window, and screen-scraping the console screen buffer.

Running an interactive application with elevated privileges within a Standard User

I am trying to open an interactive application running under the SYSTEM account within the desktop of a standard user(The interactive application has Administrative Privileges). I know this is generally not possible due to session isolation etc. However, I have witnessed applications which does so.
#pragma comment(lib, "advapi32.lib")
using namespace std;
STARTUPINFO GetStartupInfo()
{
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = const_cast<LPWSTR>(_T("Winsta0\\default"));
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_SHOW;
return startupInfo;
}
HANDLE SetInfoOnToken(HANDLE existingToken)
{
HANDLE duplicateToken;
DWORD TokenSessionId = 1;
DuplicateTokenEx(existingToken, MAXIMUM_ALLOWED, nullptr, SECURITY_IMPERSONATION_LEVEL::SecurityIdentification, TOKEN_TYPE::TokenPrimary, &duplicateToken);
SetTokenInformation(duplicateToken, TOKEN_INFORMATION_CLASS::TokenSessionId, &TokenSessionId, sizeof(TokenSessionId));
return duplicateToken;
}
bool SetTcbPrivilege(HANDLE hToken)
{
TOKEN_PRIVILEGES tp;
LUID luid;
bool success = LookupPrivilegeValue(NULL, _T("SeTcbPrivilege"), &luid);
if (!success) {
wcout << GetLastError();
return false;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges(&hToken,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),
(PTOKEN_PRIVILEGES)NULL,(PDWORD)NULL))
{
printf("AdjustTokenPrivileges error: %u\n", GetLastError());
return false;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED) return false;
}
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
{
wstring processName = _T("notepad.exe");
TCHAR* name = (wchar_t*)processName.c_str();
DWORD sessionId = 0;
STARTUPINFO startupInfo = GetStartupInfo();
PROCESS_INFORMATION processInformation;
HANDLE processHandle = nullptr;
ZeroMemory(&processInformation, sizeof(processInformation));
HANDLE hToken = GetCurrentProcessToken();
SetTcbPrivilege(hToken);
hToken = SetInfoOnToken(hToken);
bool success = false;
success = CreateProcessAsUser(hToken, nullptr, name, nullptr, nullptr, false, 0, nullptr, nullptr, &startupInfo, &processInformation);
if (success)
{
wcout << "Process started.\n";
}
else
{
wcout << "There was a problem starting the process.\n";
wcout << GetLastError();
return 0;
}
CloseHandle(processInformation.hProcess);
CloseHandle(processInformation.hThread);
return 0;
}
This code works perfectly when started normally. But when run under the SYSTEM account, it does not show the notepad window (I am aware it generally shouldn't, but that is the limitation I am trying to overcome and have seen certain apps doing so). There is however a process for notepad listed in the Task Manager.
What am I missing in the code which returns this unexpected behavior ? I am left with less samples of such scenario, so please provide any suggestions on this.
EDIT:
At this point the process does not run an leaves an ERROR_INVALID_HANDLE error. What am I doing incorrect ? Please suggest.

Make c++ program to pass input output to windows command prommpt interactively

I want to make a simple program that starts a cmd.exe parallely and takes input from the user as a command, which is then passed to the cmd.exe, after execution my program should take the output from cmd.exe and display it to the user. Basically an interface to a command prompt.
I don't want to use methods like system() as they start a new instance of cmd every time and I can't run commands like cd.
I tried it with the following code with which I am able to spawn a cmd and show initial line (copyright....), but passing commands simply returns the same line again.
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
DWORD WINAPI exec(LPVOID inputP){
char* input=(char*) inputP;
HANDLE stdinRd, stdinWr, stdoutRd, stdoutWr;
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, true};
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD stuff;
char buff[1000];
//Create the main transfer pipe
if(!CreatePipe(&stdinRd, &stdinWr, &sa, 0) || !CreatePipe(&stdoutRd,&stdoutWr, &sa, 0)) {
cout<<"Pipe creation failed"<<endl;
}
//Get Process Startup Info
GetStartupInfo(&si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
si.hStdOutput = stdoutWr;
si.hStdError = stdoutWr;
si.hStdInput = stdinRd;
//Create the CMD Shell using the process startup info above
if(!CreateProcess("C:\\Windows\\System32\\cmd.exe", NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
cout<<"Error Spawning Command Prompt."<<endl;
}
//Main while(1) Loop
while(1)
{
Sleep(100);
//Check if cmd.exe has not stoped
GetExitCodeProcess(pi.hProcess, &stuff);
//Stop the while loop if not active
if(stuff != STILL_ACTIVE) break;
//Copy Data from buffer to pipe and vise versa
PeekNamedPipe(stdoutRd, NULL, 0, NULL, &stuff, NULL);
ZeroMemory(buff, sizeof(buff));
//Read Console Output
ReadFile(stdoutRd, buff, 1000, &stuff, NULL);
//output
cout<<buff<<endl;
//Read data from stream and pipe it to cmd.exe
WriteFile(stdinWr, input, strlen(input), &stuff, NULL);
}
return 0;
}
int main() {
while(1){
char a[100];
cin>>a;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)exec, (LPVOID)a, 0, NULL);
}
}
Found my problem, was quite silly. Just need to pass a new line character so that cmd interprets the data as a command, i.e.,
cin>>a;
strcat(a,"\n");
and obviously make a single instance of cmd by calling the thread only once and passing parameters through global variables.

Win32 API : User Impersonation technique to run a process as some other user?

I'm writing an application which runs a third-party executable as some less privileged user
on Windows. I used following Win32 API functions for this:
LogonUser(L"UserName", L"Domain", NULL, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &hToken)
then calling
CreateProcessAsUser()
using hToken I've got to run the process. My actual program which launches this executable is running as Administrator. My doubts here are:
If UAC(User Account Control) is enabled. Will this work??
I need to create the processes many times. Can I use the hToken by
saving it somewhere.
Does
CreateProcessAsUser() works with different combinations of
Domain\User i.e .\Administrator or \Administrator or
Domain\UserName etc..??
The MSDN says: "Generally, it is best to use CreateProcessWithLogonW to create a process with alternate credentials." The following example demonstrates how to call this function.
#include <windows.h>
#include <stdio.h>
#include <userenv.h>
void DisplayError(LPWSTR pszAPI)
{
LPVOID lpvMessageBuffer;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&lpvMessageBuffer, 0, NULL);
//
//... now display this string
//
wprintf(L"ERROR: API = %s.\n", pszAPI);
wprintf(L" error code = %d.\n", GetLastError());
wprintf(L" message = %s.\n", (LPWSTR)lpvMessageBuffer);
//
// Free the buffer allocated by the system
//
LocalFree(lpvMessageBuffer);
ExitProcess(GetLastError());
}
void wmain(int argc, WCHAR *argv[])
{
DWORD dwSize;
HANDLE hToken;
LPVOID lpvEnv;
PROCESS_INFORMATION pi = {0};
STARTUPINFO si = {0};
WCHAR szUserProfile[256] = L"";
si.cb = sizeof(STARTUPINFO);
if (argc != 4)
{
wprintf(L"Usage: %s [user#domain] [password] [cmd]", argv[0]);
wprintf(L"\n\n");
return;
}
//
// TO DO: change NULL to '.' to use local account database
//
if (!LogonUser(argv[1], NULL, argv[2], LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, &hToken))
DisplayError(L"LogonUser");
if (!CreateEnvironmentBlock(&lpvEnv, hToken, TRUE))
DisplayError(L"CreateEnvironmentBlock");
dwSize = sizeof(szUserProfile)/sizeof(WCHAR);
if (!GetUserProfileDirectory(hToken, szUserProfile, &dwSize))
DisplayError(L"GetUserProfileDirectory");
//
// TO DO: change NULL to '.' to use local account database
//
if (!CreateProcessWithLogonW(argv[1], NULL, argv[2],
LOGON_WITH_PROFILE, NULL, argv[3],
CREATE_UNICODE_ENVIRONMENT, lpvEnv, szUserProfile,
&si, &pi))
DisplayError(L"CreateProcessWithLogonW");
if (!DestroyEnvironmentBlock(lpvEnv))
DisplayError(L"DestroyEnvironmentBlock");
CloseHandle(hToken);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}

Is there any way of stopping _popen opening a dos window?

I am using _popen to start a process to run a command and gather the output
This is my c++ code:
bool exec(string &cmd, string &result)
{
result = "";
FILE* pipe = _popen(cmd.c_str(), "rt");
if (!pipe)
return(false);
char buffer[128];
while(!feof(pipe))
{
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
_pclose(pipe);
return(true);
}
Is there any way of doing this without a console window opening (as it currently does at the _popen statement)?
On Windows, CreateProcess with a STARTUPINFO structure that has dwFlags to include STARTF_USESSHOWWINDOW. Then setting STARTUPINFO.dwFlags to SW_HIDE will cause the console window to be hidden when triggered. Example code (which may be poorly formatted, and contains a mix of C++ and WinAPI):
#include <windows.h>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
void printError(DWORD);
int main()
{
STARTUPINFOA si = {0};
PROCESS_INFORMATION pi = { 0 };
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
BOOL result = ::CreateProcessA("c:/windows/system32/notepad.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if(result == 0) {
DWORD error = ::GetLastError();
printError(error);
std::string dummy;
std::getline(std::cin, dummy);
return error;
}
LPDWORD retval = new DWORD[1];
::GetExitCodeProcess(pi.hProcess, retval);
cout << "Retval: " << retval[0] << endl;
delete[] retval;
cout << "Press enter to continue..." << endl;
std::string dummy;
std::getline(std::cin, dummy);
return 0;
}
void printError(DWORD error) {
LPTSTR lpMsgBuf = nullptr;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
cout << reinterpret_cast<char*>(lpMsgBuf) << endl;
LocalFree(lpMsgBuf);
}
As far as I know, you can't1: you are starting a console application (cmd.exe, that will run the specified command), and Windows always creates a console window when starting a console application.
although, you can hide the window after the process started, or even create it hidden if you pass the appropriate flags to CreateProcess; problem is, _popen do not pass these flags, so you have to use the Win32 APIs instead of _popen to create your pipe.
[Final Edit]
a similar SO question merges everything said above and gets you your output
C++ popen command without console
[Edited again]
erk. sorry I got excited about spawning processes. I reread your q. and apart from the extra window you're actually trying to get the processes's stdout/stderr. I'd just like to add that for that purpose, all my suggestions are sadly irrelevant. but I'll leave them here for reference.
[Edited]
For no good specific reason (except that "open" works for both windows and macs), I use ShellExecute for spawning processes rather than CreateProcess. I'll research that later..but here is my StartProcess function.
Hidden or Minimized seem to produce the same result. the cmd window does come into being but it is minimized and doesn't ever pop up on the desktop which might be your primary goal.
#if defined(PLATFORM_WIN32)
#include <Windows.h>
#include <shellapi.h>
#elif defined(PLATFORM_OSX)
#include <sys/param.h>
#endif
namespace LGSysUtils
{
// -----------------------------------------------------------------------
// pWindow : {Optional} - can be NULL
// pOperation : "edit", "explore", "find", "open", "print"
// pFile : url, local file to execute
// pParameters : {Optional} - can be NULL otherwise a string of args to pass to pFile
// pDirectory : {Optional} - set cwd for process
// type : kProcessWinNormal, kProcessWinMinimized, kProcessWinMaximized, kProcessHidden
//
bool StartProcess(void* pWindow, const char* pOperation, const char* pFile, const char* pParameters, const char* pDirectory, LGSysUtils::eProcessWin type)
{
bool rc = false;
#if defined(PLATFORM_WIN32)
int showCmd;
switch(type)
{
case kProcessWinMaximized:
showCmd = SW_SHOWMAXIMIZED;
break;
case kProcessWinMinimized:
showCmd = SW_SHOWMINIMIZED;
break;
case kProcessHidden:
showCmd = SW_HIDE;
break;
case kProcessWinNormal:
default:
showCmd = SW_NORMAL;
}
int shellRC = (int)ShellExecute(reinterpret_cast<HWND>(pWindow), pOperation,pFile,pParameters,pDirectory,showCmd);
//Returns a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise.
if( shellRC > 32 )
{
rc = true;
}
#elif defined(PLATFORM_OSX)
char cmd[1024];
sprintf(cmd, "%s %s", pOperation, pFile);
int sysrc = system( cmd );
dbPrintf("sysrc = %d", sysrc);
rc = true;
#endif
return rc;
}
}
[and previously mentioned]
If you are in control of the source code for the application that is launched, you could try adding this to the top of your main.cpp (or whatever you have named it)
// make this process windowless/aka no console window
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
You could also feed those options to the linker directly. The above is easier to play with for different build configurations imho.