我需要获得运行测试的桌面的分辨率。以前我是这样解决的:
Screen screen = Screen.PrimaryScreen;
int screenWidth = screen.Bounds.Width;
int screenHeight = screen.Bounds.Height;
不幸的是,System.Windows.Forms无法再使用了。我的项目是 .NET Core,所以我最好需要一个 NuGet 包。
如果有人有任何建议,我将不胜感激。
我需要获得运行测试的桌面的分辨率。以前我是这样解决的:
Screen screen = Screen.PrimaryScreen;
int screenWidth = screen.Bounds.Width;
int screenHeight = screen.Bounds.Height;
不幸的是,System.Windows.Forms无法再使用了。我的项目是 .NET Core,所以我最好需要一个 NuGet 包。
如果有人有任何建议,我将不胜感激。
如果您不想使用System.Windows.Forms(或不能),您可以使用 Windows API 函数获取屏幕分辨率EnumDisplaySettings。
要调用 WinAPI 函数,可以使用 .NET Core 上也提供的 P/Invoke 功能。请注意,这仅适用于 Windows 系统,因为在非 Windows 目标上没有 WinAPI。
函数声明如下所示:
[DllImport("user32.dll")]
static extern bool EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE devMode);
您还需要 WinAPIDEVMODE结构定义:
[StructLayout(LayoutKind.Sequential)]
struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public int dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
实际上,您不需要此结构的大部分字段。有趣的是dmPelsWidth和dmPelsHeight。
像这样调用函数:
const int ENUM_CURRENT_SETTINGS = -1;
DEVMODE devMode = default;
devMode.dmSize = (short)Marshal.SizeOf(devMode);
EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref devMode);
dmPelsWidth现在您可以在结构的和dmPelsHeight字段中检查屏幕分辨率devMode。
由于我们指定null为第一个参数,因此该函数描述了正在运行调用线程的计算机上的当前显示设备。