質問

I have to get the names of all available power schemes in windows 7. I try to enumerate them with the power management functions and I do get the right amount but when I call "PowerReadFriendlyName" (http://msdn.microsoft.com/en-us/library/windows/desktop/aa372740%28v=vs.85%29.aspx) it works sometimes and fails sometimes:

UCHAR   displayBuffer[256];
DWORD   displayBufferSize = sizeof(displayBuffer);
GUID    buffer;
DWORD   bufferSize = sizeof(buffer);
int     index;
int     fail=0,ok=0;
//
for(index = 0 ; ; index++)
{   ZeroMemory(&buffer, sizeof(buffer));
    ZeroMemory(&displayBuffer, sizeof(displayBuffer));
    if (PowerEnumerate(NULL,NULL,NULL, ACCESS_SCHEME,index,(UCHAR*)&buffer,&bufferSize) == ERROR_SUCCESS)
    {   if (PowerReadFriendlyName(NULL, &buffer,&NO_SUBGROUP_GUID,NULL,displayBuffer,&displayBufferSize) == ERROR_SUCCESS)
        {   ok++;
            // stuff to todo
        }
        else
        {   fail++;
            // why?
        }
    }
    else
    {   break;
    }
}

At first I had 2 custom power schemes and the retrieval of their name always failed. The standard 3 power schemes (high performance, balanced, power saver) always worked.

So I thought it had to do with the custom schemes and I manually added 2 more of them. But as it turns out now one of them actually works and I can get its name (both were derived from balanced).

I then manually added another 2 custom schemes (this time derived from power saver) and this time both seemed to work. I now have 9 in total and I can get the names of 6 of them. I cannot get the name of the 2 original custom power schemes (both derived from balanced) as well as the 2nd of the ones I added the first time.

When I type "powercfg -list" in a console I can get the list of all power schemes, but how can I get the names of all power schemes reliably in c++ without redirecting/parsing the console but using the windows power management functions?

役に立ちましたか?

解決

The documentation of the PowerReadFriendlyName() function does not mention that the variable holding the length of the buffer gets overwritten in a successful call with a non-NULL buffer. It has therefore be set before each call of PowerReadFriendlyName() or it can fail:

UCHAR   displayBuffer[2048];
DWORD   displayBufferSize;
GUID    buffer;
DWORD   bufferSize = sizeof(buffer);
int     index;
int     fail=0,ok=0;
//
for(index = 0 ; ; index++)
{   ZeroMemory(&buffer, sizeof(buffer));
    ZeroMemory(&displayBuffer, sizeof(displayBuffer));
    if (PowerEnumerate(NULL,NULL,NULL, ACCESS_SCHEME,index,(UCHAR*)&buffer,&bufferSize) == ERROR_SUCCESS)
    {   displayBufferSize = sizeof(displayBuffer);
        if (PowerReadFriendlyName(NULL, &buffer,&NO_SUBGROUP_GUID,NULL,displayBuffer,&displayBufferSize) == ERROR_SUCCESS)
        {   ok++;
            // stuff to todo
        }
        else
        {   fail++;
        }
    }
    else
    {   break;
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top