1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
// RunApp.cpp
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
DWORD
RunApp(const char* appPath, const char* cmdLine)
{
DWORD dwRet = NOERROR;
char windowTitle[256] = "EXAMPLE CONSOLE"; // this is passed to non-const
// char* param, so make sure it's a real buffer (by giving it a size)
STARTUPINFO startupInfo = {0};
startupInfo.cb = sizeof(STARTUPINFO);
startupInfo.lpTitle = windowTitle;
// can use startupInfo.wShowWindow to create window initially hidden
// see MSDN entries for CreateProcess/STARTUPINFO
PROCESS_INFORMATION processInfo = {0};
// cmdLine is also passed to non-const char* param
const size_t bufferSize = 1024;
char cmdLineBuffer[bufferSize] = {0};
if(NULL != cmdLine)
strncpy_s(cmdLineBuffer, bufferSize, cmdLine, _TRUNCATE);
BOOL bRet = CreateProcess( appPath
, cmdLineBuffer
, NULL // process security attributes
, NULL // thread security attributes
, FALSE // bInheritHandles
, CREATE_NEW_CONSOLE // dwCreationFlags
, NULL // lpEnvironment
, NULL // lpCurrentDirectory
, &startupInfo
, &processInfo );
if(FALSE != bRet)
{
Sleep(250); // give the window a chance to appear
// (can't use WaitForInputIdle with console app)
HWND hWnd = FindWindow(NULL, windowTitle);
if(NULL != hWnd)
{
const DWORD twoSecs = 2000; // in millisecs
// Wait, Hide, Wait, Show window
std::cout << "Sleeping for 2 seconds..." << std::endl;
Sleep(twoSecs);
std::cout << "Hide window" << std::endl;
ShowWindow(hWnd, SW_HIDE);
std::cout << "Sleeping for 2 seconds..." << std::endl;
Sleep(twoSecs);
std::cout << "Show window" << std::endl;
ShowWindow(hWnd, SW_SHOW);
}
else
{
std::cerr << "Failed to find window" << std::endl;
}
CloseHandle(processInfo.hThread);
CloseHandle(processInfo.hProcess);
}
else
{
dwRet = GetLastError();
std::cerr << "Failed to create process (" << dwRet << ")" << std::endl;
}
return dwRet;
}
int main(int argc, char* argv[])
{
if(2 != argc)
{
std::cerr << "RunApp <console app path>" << std::endl;
return 0;
}
const char* appPath = argv[1];
const char* cmdLine = NULL; // might be useful someday?
DWORD dwRet = RunApp(appPath, cmdLine);
return (int)dwRet;
}
|