Link to home
Start Free TrialLog in
Avatar of tullhead
tullheadFlag for United States of America

asked on

How to: simple C++ example of GetProcessByName

In a Microsoft article, I found this example:

#using <mscorlib.dll>
#using <System.dll>

using namespace System;
using namespace System::Diagnostics;
using namespace System::ComponentModel;

int MyProcedure()
{
    // Get all instances of Notepad running on the computer
    Process* localByName[] = Process::GetProcessesByName(S"notepad");
}

Using VS2010 and C++ I would like to make a little app to run this code.  In my attempt, it yielded the error that I must use /clr -- so I tried setting that, then it said it was incompatible with another setting, and so on, and so on.   I'm an old VS 6.0 and MFC C++ programmer - but just starting in .NET and don't know what "managed code is", etc.  Could someone give me a couple pointers on creating the world's simplest app that executes the code above?
Avatar of Zoppo
Zoppo
Flag of Germany image

Hi tullhead,

'managed code' means the C++ source code is compiled into an intermediate language (CIL, Common Interface Language). This language is later interpreted/compiled by the .NET runtime.

To use .NET/managed code in a C++ application you need to set the project's Configuration Properties->General->Common Language Runtime Support to Common Language Runtime Support (/clr).

To learn more about .NET maybe you should start reading http://en.wikipedia.org/wiki/.NET_Framework.

Hope that helps,

ZOPPO
This code should not compile

int MyProcedure()
{
    // The ^ is for a managed reference.
    Process^ localByName[] = Process::GetProcessesByName(S"notepad");
}

Since you are using VS 2010 there's an easier construct

auto localByName = Process::GetProcessesByName(S"notepad");

--------

Also, why not start with a new project and select CLR project type? That should create a project with all correct settings in place.

Please post errors so that someone can provide the right answer.
If you need something similar in unmanaged C++, you could use the following code from http://msdn.microsoft.com/en-us/library/windows/desktop/ms682623%28v=vs.85%29.aspx ("Enumerating All Processes (Windows)"):

#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

void PrintProcessNameAndID( DWORD processID )
{
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

    // Get a handle to the process.

    HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                   PROCESS_VM_READ,
                                   FALSE, processID );

    // Get the process name.

    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
             &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, szProcessName, 
                               sizeof(szProcessName)/sizeof(TCHAR) );
        }
    }

    // Print the process name and identifier.

    _tprintf( TEXT("%s  (PID: %u)\n"), szProcessName, processID );

    // Release the handle to the process.

    CloseHandle( hProcess );
}

int main( void )
{
    // Get the list of process identifiers.

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    {
        return 1;
    }


    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the name and process identifier for each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        if( aProcesses[i] != 0 )
        {
            PrintProcessNameAndID( aProcesses[i] );
        }
    }

    return 0;
}

Open in new window


Upon finding the process in question, just call 'OpenProcess()' with the ID you found.
Avatar of tullhead

ASKER

JKR -- I had briefly tried that, but quickly found that I didn't have psapi.h in my system, and wasn't sure how to get it, so looked and found the more modern stuff that I asked about.  Is it relatively painless to find the psapi.h (and probably the lib / dll needed with it) ?
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks JKR -- I guess I'll learn .NET another day -- I was able to adapt the code you posted to do exactly what I wanted (just detect if a process of a certain name is running).