如何使用C ++检查进程是否正在运行 [英] How to check if a process is running or not using C++

查看:134
本文介绍了如何使用C ++检查进程是否正在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个进程没有运行,我不应该显示某些上下文菜单选项。
我正在检查进程是否正在使用进程名称。

I should not display certain context menu options if one process is not running?. I am checking if the process is running or not using the process name.

但问题是,进程名称在不同的Windows平台上显示不同的方式。

But the issue is, the process name is showing different way in different windows platforms.

即,Windows任务栏上的Windows 64位进程名称为 applicationname.exe

ie, windows 64 bit process name on windows task bar is " applicationname.exe"

有些Windows xp机器显示的进程名称与 applica〜2.exe 相同。

some windows xp machine shows the same process name as "applica~2.exe"

请让我知道方法来检查进程是否正在运行?

Please let me know the consistent way to check if the process is running or not?

我的开发环境是C ++和Visual Studio 2010

My development environment is C++ and Visual Studio 2010

   DWORD getProcessID(const std::wstring& processName)
   {
       PROCESSENTRY32 info;
       info.dwSize = sizeof(info);

       HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
       if ( snapshot == INVALID_HANDLE_VALUE )
             return 0;

       Process32First(snapshot, &info);
       if ( !processName.compare(info.szExeFile) )
       {
             CloseHandle(snapshot);
             return info.th32ProcessID;
       }

       while ( Process32Next(snapshot, &info) )
       {
              if ( !processName.compare(info.szExeFile) )
               {
                    CloseHandle(snapshot);
                    return info.th32ProcessID;
               }
       }

      CloseHandle(snapshot);
     return 0;
   }


推荐答案

EnumProcesses 是枚举活动进程的另一种方法。

EnumProcesses is the other way to enumerate active processes.

不同的是,您需要为PID分配空间,调用 EnumProcesses ,使用 PROCESS_QUERY_INFORMATION 访问标志打开每个进程,然后调用 GetProcessImageFileName 处理并进行比较。

The difference is that you need to allocate the space for PIDs,call EnumProcesses, open each process with PROCESS_QUERY_INFORMATION access flag and then call GetProcessImageFileName on it's handle and do the comparison.

这篇关于如何使用C ++检查进程是否正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆