-2

How to retrieve process handle by using application name in c++?

Is there any windows API is there? Example: Sample.exe

I have to get the handle of this sample.exe and I need to call Terminate process on that handle.

Any one suggest a good solution for this.

Note: its should support winxp and win8

Thanks in Advance

Sree
  • 21
  • 2
  • 6
  • "Sample.EXE" - so you mean the _file_ name of the executable? There's also a `ProductName` in the application's version resource. That's a bit more work to get at. – MSalters Feb 09 '16 at 11:36
  • Possible duplicate of [Get the process handle of a process by image name](http://stackoverflow.com/questions/2281205/get-the-process-handle-of-a-process-by-image-name) or [How can I get a process handle by its name in C++?](http://stackoverflow.com/q/865152/1889329) – IInspectable Feb 09 '16 at 12:46

2 Answers2

1

You should use toolhelp API's:

HANDLE OpenProcessByName(LPCTSTR Name, DWORD dwAccess)
{
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnap != INVALID_HANDLE_VALUE)
    {
        PROCESSENTRY32 pe;
        ZeroMemory(&pe, sizeof(PROCESSENTRY32));
        pe.dwSize = sizeof(PROCESSENTRY32);
        Process32First(hSnap, &pe);
        do
        {
            if (!lstrcmpi(pe.szExeFile, Name))
            {
                return OpenProcess(dwAccess, 0, pe.th32ProcessID);
            }
        } while (Process32Next(hSnap, &pe));

    }
    return INVALID_HANDLE_VALUE;
}

For example:

#include <windows.h>
#include <tlhelp32.h>

//...

int main()
{

    HANDLE hFire = OpenProcessByName("firefox.exe", PROCESS_VM_READ);
    cout << "Handle: " << hFire << endl;
    CloseHandle(hFire);
    cin.get();
    return 0;
}

But you should be careful because if there are more than 1 copy of process you will get a handle of the first. To handle all processes in "return OpenProcess" use call of some function like Handler(OpenProcess(dwAccess, 0, pe.th32ProcessID)):

void Handler(HANDLE hndl)
{
  //... work with your Handle
  CloseHandle(hndl);
}
//...
if (!lstrcmpi(pe.szExeFile, Name))
{
    Handler(OpenProcess(dwAccess, 0, pe.th32ProcessID)):
}
//...
Mark Volt
  • 15
  • 3
  • Should be noted that this version return the hanlde of the first matching found, whereas there may be multiple instances of the file currenlty running. – mikedu95 Feb 09 '16 at 10:23
  • I noted it, look better, quote: "But you should be careful because if there are more than 1 copy of process you will get a handle of the first". After i post code for every process – Mark Volt Feb 09 '16 at 13:33
0

To fetch the process name from process id see quiestions: get process name from process id (win32) or How to get the process name in C++

Enumerate process documentation https://msdn.microsoft.com/en-us/library/windows/desktop/ms682629%28v=vs.85%29.aspx Example code: https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms682623%28v=vs.85%29.aspx

EDIT: There is solution that does not have problem "return the hanlde of the first matching found, whereas there may be multiple instances". This solution return array of pairs ProcessId and names, and you can select that you need in simple loop.

#include <windows.h>
#include <tlhelp32.h>

#include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <map>

typedef std::pair<DWORD,std::string> ProcessVectorEntry;
typedef std::vector<ProcessVectorEntry> ProcessVector;

void getProcessInformation( ProcessVector& processVector ) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hSnapshot) {
        PROCESSENTRY32 pe32;
        pe32.dwSize = sizeof(PROCESSENTRY32);
        if(Process32First(hSnapshot, &pe32)) {
            do {
               processVector.push_back( ProcessVectorEntry( pe32.th32ProcessID, pe32.szExeFile ) );
            } while(Process32Next(hSnapshot, &pe32));
         }
         CloseHandle(hSnapshot);
    }
}

And simple search in main

int main() {
  std::string search = "firefox.exe";

  ProcessVector processVector;
  getProcessInformation( processVector );

  std::cout << "Process IDs contains " << search << " in name:" << std::endl;

  for( int i=0; i<processVector.size(); ++i )
    if( processVector[i].second.find(search) != std::string::npos )
      std::cout << processVector[i].first << std::endl;

  return 0;
}
Community
  • 1
  • 1
oklas
  • 7,935
  • 2
  • 26
  • 42
  • I know you want to get your answer in first, but it's not worth it if it's only half written, full of typos, doesn't name the API function accurately. Hence my downvote. I advise you to take a little more time polishing the answer before pushing the **Post Your Answer** button. – David Heffernan Feb 09 '16 at 08:32
  • Thanks You. I am novice here, I have not know that this is move tone. I will later write more full answer before post later. Hope for understanding. – oklas Feb 09 '16 at 08:36
  • The question is how to get process handle form an executable image name. Though a synthetsis of your links could lead to that after some adaptations, you didn't explained that clearly enough. – mikedu95 Feb 09 '16 at 10:22
  • It is enough for task solving. There are many duplications of task solutions and examples in links. – oklas Feb 09 '16 at 11:26