如何使用Qt(C ++)检查程序是否按其名称运行 [英] How to check if a program is running by its name with Qt (C++)

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

问题描述

如何使用Qt(C ++)来检查程序是否正在运行.

How to check if a program is running, by its name, with Qt (C++).

QProcess :: pid 会完成这项工作吗?我不知道该怎么用.请提出建议.

Will QProcess::pid do the job? I don't know how to use it. Please suggest.

推荐答案

据我所知,QProcess不允许您这样做(除非您自己生成了该过程),实际上Qt不会这样做.但是Win32 API提供了一种通过 EnumProcesses 函数实现所需功能的方法,并且在Microsoft网站上提供了如何使用它的完整示例:

As far as I know QProcess won't allow you to do that (unless you've spawned the process yourself) and in fact nothing in Qt will. However Win32 API provides a way to achieve what you want through EnumProcesses function and a complete example of how to use it is provided at Microsoft website:

http://msdn.microsoft.com/en-us/library/ms682623.aspx

要获取此信息,请使用以下函数替换PrintProcessNameAndID:

To get you need replace PrintProcessNameAndID with the following function:

bool matchProcessName( DWORD processID, std::string processName)
{
    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) );
        }
    }

    // Compare process name with your string        
    bool matchFound = !_tcscmp(szProcessName, processName.c_str() );

    // Release the handle to the process.    
    CloseHandle( hProcess );

    return matchFound;
}

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

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