开发者

how to use window title to get process id,and process name

I would like t开发者_JAVA技巧o get process id and process name via using window title my develop environment is visual c++ 2008

how to do it.

thanks


It's not reliable to search window by title. But if you want to do so, first you need to find window handle for specified title. You can easily do this with EnumWindows function. When you find HWND you can use GetWindowThreadProcessId function to get process id.

UPD: To get process name you need to get process handle with OpenProcess and use GetProcessImageFileName.


HWND hw = FindWindow(NULL, L"Window Title");

if (hw)
{
    DWORD dwProcessId = 0;
    DWORD dwThreadId = GetWindowThreadProcessId(hw, &dwProcessId);

    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwProcessId);

    if (hProcess)
    {
         wchar_t *szExeName[1024] = {0};
         if (QueryFullProcessImageName(hProcess, 0, szExeName, _countof(szExeName))
         {
            // ...
         }
         CloseHandle(hProcess);
    }
}

You should probably use the class argument as well (the one that is NULL in my first line) if you know it, so that it is less likely you will accidentally find some other program's window that happens to have the same title.

Of course, the class name is not guaranteed to be unique between programs either, but the combination is more reliable than just using the title by itself.

You can get the window class easily using Spy++.

Edit: QueryFullProcessImageName requires Vista, but you can swap that line for one which uses GetProcessImageFileName as per DReJ's answer.

Edit2: If you're not compiling for unicode, remove the "L" before "Window Title" and use a char buffer instead of wchar_t.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜