cr1gger
@cr1gger
Все дороги ведут в Рим — встретимся в Риме!

LPCWSTR как сделать чтобы работало?

СПОЙЛЕР CPP

#include "ProcessCatcher.h"


char process_path[MAX_PATH];
DWORD getProcessPath(DWORD processId) {
    HANDLE handle = NULL;
    DWORD str;
    handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, processId);
    if (handle != NULL)
    {
        str = GetModuleFileNameExA(handle, NULL, process_path, MAX_PATH);
        CloseHandle(handle);
        return str;
    }
    return false;
}

std::wstring GetShellPropStringFromPath(LPCWSTR pPath, PROPERTYKEY const& key)
{
    // Use CComPtr to automatically release the IShellItem2 interface when the function returns
    // or an exception is thrown.
    CComPtr<IShellItem2> pItem;
    HRESULT hr = SHCreateItemFromParsingName(pPath, nullptr, IID_PPV_ARGS(&pItem));
    if (FAILED(hr))
        throw std::system_error(hr, std::system_category(), "SHCreateItemFromParsingName() failed");

    // Use CComHeapPtr to automatically release the string allocated by the shell when the function returns
    // or an exception is thrown (calls CoTaskMemFree).
    CComHeapPtr<WCHAR> pValue;
    hr = pItem->GetString(key, &pValue);
    if (FAILED(hr))
        throw std::system_error(hr, std::system_category(), "IShellItem2::GetString() failed");

    // Copy to wstring for convenience
    return std::wstring(pValue);
}
void StartSearcher(void* pParams)
{
    while (true)
    {
        bool step1 = false;
        bool step2 = false;
        bool step3 = false;

        PROCESSENTRY32 peProcessEntry;
        TCHAR szBuff[1024];
        DWORD dwTemp;
        HANDLE CONST hSnapshot = CreateToolhelp32Snapshot(
            TH32CS_SNAPPROCESS, 0);
        if (INVALID_HANDLE_VALUE == hSnapshot) {
            return;
        }

        peProcessEntry.dwSize = sizeof(PROCESSENTRY32);
        Process32First(hSnapshot, &peProcessEntry);
        do {
            if (0 == lstrcmpW(peProcessEntry.szExeFile, L"File.exe"))
            {
                step1 = true;
            }
            getProcessPath(peProcessEntry.th32ProcessID);
            
            std::cout << process_path << "\n"; // выводит норм.
            try {
                std::wstring file_desc = GetShellPropStringFromPath(process_path, PKEY_FileDescription);
                std::wstring file_corp = GetShellPropStringFromPath((LPCWSTR)process_path, PKEY_Software_ProductName);
                if (file_desc == L"File description") {
                    step2 = true;
                }
            }
            catch (std::system_error const& e) {
                std::wcout << L"ERROR: " << e.what() << L"\nError code: " << e.code() << std::endl;
                continue;
            }
        } while (Process32Next(hSnapshot, &peProcessEntry));

        CloseHandle(hSnapshot);

        if (step1 || step2 || step3)
        {
            std::cout << "Process found!";
        }

        Sleep(1000);
    }
}


СПОЙЛЕР .h

#pragma once
#include <ShlObj.h>    // Shell API
#include <Propkey.h>   // PKEY_* constants
#include <atlbase.h>   // CComPtr, CComHeapPtr
#include <string>
#include <iostream>
#include <psapi.h>
#include <Windows.h>
#include <io.h>
#include <fcntl.h>
#include <system_error>
#include <WtsApi32.h>
#include <tlhelp32.h>
DWORD getProcessPath(DWORD processId);
std::wstring GetShellPropStringFromPath(LPCWSTR pPath, PROPERTYKEY const& key);
void StartSearcher(void* pParams);

Подскажите, пожалуйста.
Моя задача: мне нужно перебирая все процессы, проверять его name.exe и description если хотябы один совпал то пишем что нашёл!
step1 работает по имени процесса ищет.
А step2 не работает, получение description выдает исключение (GetShellPropStringFromPath)
Я так понимаю это из за того что типы не совпадают.

В примере автор указывал вообще вот так путь до файла, у меня так не получится, т.к моя функция возвращает путь файла в DWORD:
LPCWSTR path = LR"(C:\Program Files\WindowsApps\Microsoft.Windows.Photos_2018.18061.17410.0_x64__8wekyb3d8bbwe\Microsoft.Photos.exe)";


Что делать не знаю уже.
  • Вопрос задан
  • 160 просмотров
Решения вопроса 1
@Sumor
У вас перемешаны char и wchar_t.
Тогда уж:
wchar_t process_path[MAX_PATH];
иначе у вас получается массив пустых указателей.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы