: How to get Process.name from processID


void GetProcessNameByProcessID(DWORD PID, std::wstring &name)
{
	//Moe Suzuki

	HANDLE hProceess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, PID);
	if (hProceess==NULL)
	{
		name = _TEXT("none");
		return;
	}

	size_t short_path_buffer_size = MAX_PATH > 4192 ? MAX_PATH : 4192;

	std::vector short_path_buffer(short_path_buffer_size);

	TCHAR *buf_short_name = &short_path_buffer.at(0);

	DWORD short_name_return = GetModuleFileNameEx(hProceess, 0, buf_short_name, short_path_buffer_size);
	if(short_name_return==0)
	{
		name = _TEXT("none");
		CloseHandle(hProceess);
		return;
	}

	DWORD long_path_size = GetFullPathName(buf_short_name, 0, NULL, NULL);
	if (long_path_size == 0)
	{
		name = _TEXT("none");
		CloseHandle(hProceess);
		return;
	}

	long_path_size += 128;
	std::vector buffer_full_path(long_path_size);
	TCHAR *full_path_buffer = &buffer_full_path.at(0);
	TCHAR *buf_long_name = &buffer_full_path.at(0);
	TCHAR *filename;

	long_path_size = GetFullPathName(buf_short_name, long_path_size, full_path_buffer, &filename);
	if (long_path_size == 0)
	{
		name = _TEXT("none");
		CloseHandle(hProceess);
		return;
	}

	char buf[4096];
	if (sizeof(TCHAR) == 1) {
		sprintf_s(buf, 4096, "filename = %s \r\n", filename);
	}else {
		sprintf_s(buf, 4096, "filename = %ls \r\n", filename);
		name = filename;

	}
	OutputDebugStringA(buf);
	CloseHandle(hProceess);

}

Leave a Reply

メールアドレスが公開されることはありません。

注意(NOTICE)

コメントの投稿は反映までに時間がかかる場合があります。 Post Comments may take some minutes to publish.