【发布时间】:2010-03-08 16:16:30
【问题描述】:
如何检索我的 C# Winform 应用程序运行时的屏幕分辨率?
【问题讨论】:
如何检索我的 C# Winform 应用程序运行时的屏幕分辨率?
【问题讨论】:
您是否只需要标准应用程序将使用的区域,即不包括 Windows 任务栏和停靠窗口?如果是这样,请使用Screen.WorkingArea property。否则,请使用Screen.Bounds。
如果有多个监视器,您需要从表单中抓取屏幕,即
Form myForm;
Screen myScreen = Screen.FromControl(myForm);
Rectangle area = myScreen.WorkingArea;
如果您想知道哪个是主显示屏,请使用Screen.Primary 属性。此外,您可以从Screen.AllScreens 属性中获取屏幕列表。
【讨论】:
就目前而言,给出的答案是正确的。但是,当您将文本大小设置为超过 125% 时,Windows(和 .NET)会开始调整屏幕大小,以便为您进行自动缩放。
大多数时候,这不是问题 - 您通常希望 Windows 和 .NET 执行此操作。但是,如果您确实需要知道屏幕上的实际像素数(例如,您想直接绘制到桌面 DC),您可以执行以下操作。我只在win10上试过。其他 Windows 版本上的 YMMV。
到目前为止,如果您不想在应用中全局关闭 DPI 感知,这是我发现获得真实屏幕像素数的唯一方法。请注意,此示例获取主显示尺寸 - 您需要修改它以获取其他屏幕。
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
[DllImport("gdi32.dll")]
static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
IntPtr primary = GetDC(IntPtr.Zero);
int DESKTOPVERTRES = 117;
int DESKTOPHORZRES = 118;
int actualPixelsX = GetDeviceCaps(primary, DESKTOPHORZRES);
int actualPixelsY = GetDeviceCaps(primary, DESKTOPVERTRES);
ReleaseDC(IntPtr.Zero, primary);
【讨论】:
使用 Screen 类,并询问 Bounds 属性。 Screen 类有一个用于Primary Screen 的静态属性,以及另一个返回a list of all the screens attached to the system 的静态属性。
【讨论】:
Screen.PrimaryScreen.WorkingArea.Size()
【讨论】:
这是我用来获取鼠标指针所在工作区的屏幕分辨率的方法。我可以启动我的程序,然后将鼠标移到另一台显示器上并获得该分辨率。
internal static void GetScreenResolution(ref double screenX, ref double screenY)
{
Screen myScreen = Screen.FromPoint(Cursor.Position);
System.Drawing.Rectangle area = myScreen.WorkingArea;
screenX = area.Width;
screenY = area.Height;
}
也许不是最好的解决方案,但我可以生成一个缩放因子并使用它来缩放我的控件。
我在 WPF 程序中使用了它,我必须添加一个引用 System.Windows.Forms
我还将它放在一个单独的类中,这样我的主代码中就不会发生冲突。
【讨论】: