问题
I want to set the width & height of a Window
dynamically based on the user screens maximum width/height. How can I determine this programmatically?
回答1:
For the primary screen:
System.Windows.SystemParameters.PrimaryScreenWidth
System.Windows.SystemParameters.PrimaryScreenHeight
(Note that there are also some other primary screen related properties which depend on various factors, Full*
& Maximised*
)
Virtual screen:
SystemParameters.VirtualScreenWidth
SystemParameters.VirtualScreenHeight
回答2:
If you want the specific dimensions of the monitor your program is running on (if someone is running more than one monitor) you could also use:
var helper = new WindowInteropHelper(this); //this being the wpf form
var currentScreen = Screen.FromHandle(helper.Handle);
This will return a screen object referencing the monitor the program is running on. From there you can use the currentScreen.Bounds.Width
/ Height
property (for the full size) or the currentScreen.WorkingArea.Width
/ Height
(minus task bar, etc.) depending on what you want.
回答3:
use Screen Object
Screen.PrimaryScreen.Bounds.Width
回答4:
You can use the SizeChanged
event
SizeChanged="MyWindow_SizeChanged"
Then in your event handler,
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);
}
}
where MainGrid
is a container for all the contents in MyWindow
.
回答5:
I couldn't use any of the solutions above under .NET 4.0.30319.42000 with Windows 10 Enterprise when calling it from the Ranorex Studio 8.0.1+git.8a3e1a6f, so I used the line
using WinForms = System.Windows.Forms;
[…]
SetWindowPos(processes[0].MainWindowHandle,
0,
y,
x,
WinForms.SystemInformation.PrimaryMonitorSize.Width,
WinForms.SystemInformation.PrimaryMonitorSize.Height,
SWP.SHOWWINDOW);
回答6:
You can get the screen height and width:
int height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height;
int width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width;
Then set the Window's Height
and Width
properties to those in the Initialization.
this.Height = height;
this.Width = width;
Works to get the screen's height and width in WinForms or in ASP .NET. No muss, no fuss, except you'll need to reference the System.Windows.Forms
assembly in your project if it's not a WinForm project.
来源:https://stackoverflow.com/questions/6277907/how-to-determine-the-screen-width-height-using-c-sharp