I want it to close when it opens the exe file separately

I have two exe files coded in C# and C++. What I want to do is to download and run the exe coded with C++ from C#. When the C++ application is not brought from the C# application, I do not want it to be launched directly from the downloaded folder. How can I do this?

1 answer

  • answered 2021-04-14 22:37 Remy Lebeau

    The C# app can pass a command-line parameter when it launches the C++ app. If the C++ app does not see that parameter present, it can just terminate itself immediately without doing anything else.

    Process.Start(@"c:\path to\cpp.exe", "-startedByCSharpApp");
    
    #include <string.h>
    
    bool startedByCSharpApp(int argc, char* argv[])
    {
        for(int i = 1; i < argc; ++i) {
            if (strcmp(argv[i], "-startedByCSharpApp") == 0) {
                return true;
            }
        }
        return false;
    }
    
    int main(int argc, char* argv[])
    {
        if (startedByCSharpApp(argc, argv))
        {
            // normal operations here ...
        }
        return 0;
    }
    

    Another option would be to have the C++ app call CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS) and Process32First()/Process32Next() to walk the list of running processes looking for itself and the C# app. See Taking a Snapshot and Viewing Processes. If both are not found, or if the C# app's process ID does not match its own process's th32ParentProcessID, it can terminate itself immediately.

    #include <tlhelp32.h>
    #include <tchar.h>
    
    #include <vector>
    #include <algorithm>
    
    bool startedByCSharpApp()
    {
        HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (hProcessSnap == INVALID_HANDLE_VALUE)
            return false;
    
        PROCESSENTRY32 pe32;
        pe32.dwSize = sizeof(pe32);
    
        if (!Process32First(hProcessSnap, &pe32))
        {
            CloseHandle(hProcessSnap);
            return false;
        }
    
        DWORD MyProcessId = GetCurrentProcessId();
        DWORD MyParentProcessId = 0;
        std::vector<DWORD> CSharpAppPIDs;
    
        do
        {
            if (pe32.th32ProcessID == MyProcessId)
            {
                MyParentProcessId = pe32.th32ParentProcessID;
            }
            else if (_tcscmp(pe32.szExeFile, "csharp.exe") == 0)
            {
                CSharpAppPIDs.push_back(pe32.th32ProcessID);
            }
        }
        while (Process32Next(hProcessSnap, &pe32));
    
        CloseHandle(hProcessSnap);
    
        if (MyParentProcessId != 0)
            return (std::find(CSharpAppPIDs.begin(), CSharpAppPIDs.end(), MyParentProcessId) != CSharpAppPIDs.end());
    
        return false;
    }
    
    int main()
    {
        if (startedByCSharpApp())
        {
            // normal operations here ...
        }
        return 0;
    }