Arrow25
Arrow25

Reputation: 23

How to close particular application after opening it in C++?

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;
}

Upvotes: 2

Views: 1031

Answers (1)

Zeus
Zeus

Reputation: 3880

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;
}

Upvotes: 2

Related Questions