How to close particular aplication after opening it in c++?

Viewed 308

So in my code I'm opening for example notepad using ShellExecute and I want to close it after but I cannot find any working way, so my question is, what is the easiest way to close particular aplication using c++ code?

#include <iostream>
#include <Windows.h>

int main()
{

    ShellExecute(NULL, "open", "notepad", NULL, NULL, SW_SHOWDEFAULT);

    Sleep(10000);

    //here I'm missing the part that closes previously opened notepad

    return 0;

}

1 Answers

You can use ShellExecuteEx with SEE_MASK_NOCLOSEPROCESS, then you can pass it as a parameter it to the TerminateProcess function.

Here is a sample:

#include <windows.h>

int main()
{
    SHELLEXECUTEINFO lpExecInfo{};
    lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    lpExecInfo.lpFile = L"notepad.exe";
    lpExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
    lpExecInfo.hwnd = NULL;
    lpExecInfo.lpVerb = NULL;
    lpExecInfo.lpParameters = NULL;
    lpExecInfo.lpDirectory = NULL;
    lpExecInfo.nShow = SW_SHOWNORMAL;
    ShellExecuteEx(&lpExecInfo);

    Sleep(3000);
    if (lpExecInfo.hProcess)
    {
        TerminateProcess(lpExecInfo.hProcess, 0);
        CloseHandle(lpExecInfo.hProcess);
    }
    return 0;
}
Related