- 1 year ago
WPF- Resize window as per resolution when moved from one monitor to another(Dual monitor system)
To resize a WPF window automatically when moved from one monitor to another in a dual-monitor system, you can handle the SystemEvents.DisplaySettingsChanged
event and adjust the window size based on the new monitor's resolution. Here's an example of how you can achieve this:
csharpusing System;
using System.Windows;
using Microsoft.Win32;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
}
private void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
// Get the current monitor resolution
var monitor = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle);
var newWidth = monitor.Bounds.Width;
var newHeight = monitor.Bounds.Height;
// Resize the window based on the new resolution
Width = newWidth;
Height = newHeight;
}
}
}
In the above code, the SystemEvents.DisplaySettingsChanged
event is subscribed in the constructor of the MainWindow
class. When this event is triggered, the event handler SystemEvents_DisplaySettingsChanged
is called. Inside the event handler, the current monitor resolution is obtained using the System.Windows.Forms.Screen
class. The window's Width
and Height
properties are then updated with the new resolution values.
By handling the DisplaySettingsChanged
event, the window will automatically adjust its size when moved from one monitor to another, ensuring it fits the screen's resolution.
Note: Make sure to include the necessary references to System.Windows.Forms
and Microsoft.Win32
in your project for accessing the required classes and events.
Remember to unregister the SystemEvents.DisplaySettingsChanged
event when you close the window or dispose of the object to prevent memory leaks.