如何在没有 Windows 窗体参考的情况下获得屏幕分辨率?

Mik*_*ike 8 c# screen-resolution .net-core

我需要获得运行测试的桌面的分辨率。以前我是这样抓取分辨率的:

Screen screen = Screen.PrimaryScreen;
int screenWidth = screen.Bounds.Width;
int screenHeight = screen.Bounds.Height;
Run Code Online (Sandbox Code Playgroud)

不幸的是,System.Windows.Forms不能再使用了。我的项目是 .NET Core,所以我最好为此需要一个 NuGet 包。

如果有人有任何建议,我将不胜感激。

dym*_*oid 8

如果您不想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);
Run Code Online (Sandbox Code Playgroud)

您还需要 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;
}
Run Code Online (Sandbox Code Playgroud)

实际上,您不需要该结构的大部分字段。有趣的是dmPelsWidthdmPelsHeight

像这样调用函数:

const int ENUM_CURRENT_SETTINGS = -1;

DEVMODE devMode = default;
devMode.dmSize = (short)Marshal.SizeOf(devMode);
EnumDisplaySettings(null, ENUM_CURRENT_SETTINGS, ref devMode);
Run Code Online (Sandbox Code Playgroud)

现在您可以在结构体的dmPelsWidthdmPelsHeight字段中检查屏幕分辨率devMode

由于我们指定null为第一个参数,该函数描述了正在运行调用线程的计算机上的当前显示设备。

  • 这是一个 WinAPI 函数。它调用将调用转发到视频驱动程序的操作系统内部例程。视频驱动程序填充您提供的结构“DEVMODE”的信息。如果这个答案有帮助,您可以投票并接受它。 (3认同)