c# - 通过代码,我如何测试硬盘驱动器是否正在 sleep 而不唤醒它

标签 c# windows hardware

我正在构建一个小应用程序,为我提供磁盘上的可用空间。

我想添加一个显示磁盘状态的功能,例如它是否正在休眠。操作系统是 Windows。

如何做到这一点?当然,代码不应该必须唤醒磁盘才能发现;)

C# 中的解决方案会很好,但我想任何解决方案都可以...

谢谢你的帮助。

最佳答案

C++ 解决方案(调用 GetDiskPowerState 它将遍历物理驱动器直到没有更多):

class AutoHandle
{
    HANDLE  mHandle;
public:
    AutoHandle() : mHandle(NULL) { }
    AutoHandle(HANDLE h) : mHandle(h) { }

    HANDLE * operator & ()
    {
        return &mHandle;
    }

    operator HANDLE() const
    {
        return mHandle;
    }

    ~AutoHandle()
    {
        if (mHandle && mHandle != INVALID_HANDLE_VALUE)
            ::CloseHandle(mHandle);
    }
};


bool
GetDiskPowerState(LPCTSTR disk, string & txt)
{
    AutoHandle hFile = CreateFile(disk, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
    if (hFile && hFile != INVALID_HANDLE_VALUE)
    {
        BOOL powerState = FALSE;
        const BOOL result = GetDevicePowerState(hFile, &powerState);
        const DWORD err = GetLastError();

        if (result)
        {
            if (powerState)
            {
                txt += disk;
                txt += " : powered up\r\n";
            }
            else
            {
                txt += disk;
                txt += " : sleeping\r\n";
            }
            return true;
        }
        else
        {
            txt += "Cannot get drive ";
            txt += disk;
            txt += "status\r\n";
            return false;
        }
    }

    return false;
}

string 
GetDiskPowerState()
{
    string text;
    CString driveName;
    bool result = true;
    for (int idx= 0; result; idx++)
    {
        driveName.Format("\\\\.\\PhysicalDrive%d", idx);
        result = GetDiskPowerState(driveName, text);
    }
    return text;
}

关于c# - 通过代码,我如何测试硬盘驱动器是否正在 sleep 而不唤醒它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/858706/

相关文章:

c++ - openMP 的 SIMD 构造是否需要特定类型的硬件?

c++ - C++ 和 MQ 的网络硬件优先级

javascript - 64KB 在磁盘 IO 方面有什么意义,这与 JavaScript 相关吗?

c# - 是否允许在类外修改 C# 只读字段?

c# - Rabbitmq,在发布者之前重启消费者

windows - 如何将 Direct3D/WPF/DWM 窗口捕获到位图中?

python - Windows 任务计划程序不允许 python subprocess.popen

c# - 进程 WaitForExit 不等待

c# - 如何设置统一容器以创建模拟/真实记录器实例

c - 如何及时检测按钮是否被连续按下?