如果在使用 powershell 将机器的当前分辨率与标准分辨率进行比较时条件不起作用

问题描述

我想获取机器的当前分辨率并将其存储以用于与标准分辨率进行比较。我们将标准分辨率保持为 1280x1024 或 1920x1080。

我可以从这里的惊人答案 https://superuser.com/a/1437714/1280078 中获得当前分辨率作为变量 $hdc 但是我如何进一步使用 $hdc 与上述分辨率/宽度进行比较。

我在 powershell 中使用了以下代码,但它似乎不适用于 if 条件,只能转到 else 条件。我在这里做错了什么?

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
    [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd);
    [DllImport("gdi32.dll")] public static extern int GetDeviceCaps(IntPtr hdc,int nIndex);
}
"@
while ($true) #To execute following in infinite loop
{
#Check the width of the machine and store in variable $hdc
$hdc = [PInvoke]::GetDC([IntPtr]::Zero)
[PInvoke]::GetDeviceCaps($hdc,118) # Get width

#Compare with standard width in standard resolution
if(($hdc -eq 1280) -or ($hdc -eq 1920)) { #NOT Working
   write-host("Resolution is correct")
}else {
    Start-sleep -s 60
    #Wait for resolution to be set on startup and check width again
    write-host("Resolution is not correct,checking again...")
    [PInvoke]::GetDeviceCaps($hdc,118) # Get width
    
    #Compare with standard widths again,send  email if NOT equal
    if(($hdc -eq 1280) -or ($hdc -eq 1920)) {
        write-host("Resolution is correct")
    }else {
        write-host("Resolution is not correct,triggering email notification...")
        break #break loop if email is triggered
}
}
}

解决方法

宽度不存储在变量 $hdc 中,而是通过运行 [PInvoke]::GetDeviceCaps($hdc,118) 行来检索。您可以执行类似 $width = [PInvoke]::GetDeviceCaps($hdc,118) 的操作,然后在 if 中将 $hdc 替换为 $width

所以,换句话说,这样的事情应该可行。

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
    [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd);
    [DllImport("gdi32.dll")] public static extern int GetDeviceCaps(IntPtr hdc,int nIndex);
}
"@
while ($true) #To execute following in infinite loop
{
    #Check the width of the machine and store in variable $hdc
    $hdc = [PInvoke]::GetDC([IntPtr]::Zero)
    $width = [PInvoke]::GetDeviceCaps($hdc,118) # Get width

    #Compare with standard width in standard resolution
    if(($width -eq 1280) -or ($width -eq 1920)) { #NOT Working
       write-host("Resolution is correct")
    }else {
        Start-sleep -s 60
        #Wait for resolution to be set on startup and check width again
        write-host("Resolution is not correct,checking again...")
        $width = [PInvoke]::GetDeviceCaps($hdc,118) # Get width
    
        #Compare with standard widths again,send  email if NOT equal
        if(($width -eq 1280) -or ($width -eq 1920)) {
            write-host("Resolution is correct")
        }else {
            write-host("Resolution is not correct,triggering email notification...")
            break #break loop if email is triggered
}
}
}