簡體   English   中英

如何使用 C# 確定屏幕寬度/高度

[英]How to determine the screen width/height using C#

我想根據用戶屏幕的最大寬度/高度動態設置Window的寬度和高度。 如何以編程方式確定這一點?

對於主屏幕:

System.Windows.SystemParameters.PrimaryScreenWidth
System.Windows.SystemParameters.PrimaryScreenHeight

請注意,還有一些其他與主屏幕相關的屬性取決於各種因素, Full*Maximised*

虛擬屏幕:

SystemParameters.VirtualScreenWidth
SystemParameters.VirtualScreenHeight

如果您想要運行程序的監視器的特定尺寸(如果有人運行多個監視器),您還可以使用:

var helper = new WindowInteropHelper(this); //this being the wpf form 
var currentScreen = Screen.FromHandle(helper.Handle);

這將返回一個屏幕 object 引用正在運行程序的監視器。 從那里您可以根據需要使用currentScreen.Bounds.Width / Height屬性(全尺寸)或currentScreen.WorkingArea.Width / Height (減去任務欄等)。

使用屏幕 Object

Screen.PrimaryScreen.Bounds.Width

您可以使用SizeChanged事件

SizeChanged="MyWindow_SizeChanged"

然后在您的事件處理程序中,

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
    if (this.MinWidth > 0 && this.MinHeight > 0)
    {
        double heightScaleFactor = e.NewSize.Height / this.MinHeight;
        double widthScaleFactor = e.NewSize.Width / this.MinWidth;            
        mainGrid.LayoutTransform = new ScaleTransform(heightScaleFactor, widthScaleFactor);
    }
}

其中MainGridMyWindow中所有內容的容器。

當從 Ranorex Studio 8.0.1+git.8a3e1a6f 調用它時,我無法在 .NET 4.0.30319.42000 和 Windows 10 Enterprise 下使用上述任何解決方案,所以我使用了該行

using WinForms = System.Windows.Forms;
[…]
                SetWindowPos(processes[0].MainWindowHandle,
                    0,
                    y,
                    x,
                    WinForms.SystemInformation.PrimaryMonitorSize.Width,
                    WinForms.SystemInformation.PrimaryMonitorSize.Height,
                    SWP.SHOWWINDOW);

你可以得到屏幕的高度和寬度:

int height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
int width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;

然后將 Window 的HeightWidth屬性設置為 Initialization 中的屬性。

this.Height = height;
this.Width = width;

用於在 WinForms 或 ASP .NET 中獲取屏幕的高度和寬度。 沒有麻煩,沒有大驚小怪,除非您需要在您的項目中引用System.Windows.Forms程序集,如果它不是 WinForm 項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM