- 1 year ago
Keep WPF window on the current working monitor (in multiple-monitor setup) [Closed/Duplicate]
To keep a WPF window on the current working monitor in a multiple-monitor setup, you can use the following approach:
Determine the current working monitor: Retrieve the monitor where the application is currently active by using the
System.Windows.Forms.Screen
class. TheScreen.FromHandle
method can be used to get the screen associated with the application's main window.Set the window's
Left
andTop
properties: Once you have the current working monitor, you can set theLeft
andTop
properties of your WPF window to position it on that monitor. You can use theWorkingArea
property of theScreen
class to determine the available working area of the monitor and adjust the window's position accordingly.
Here's an example code snippet that demonstrates this approach:
csharpusing System.Windows;
using System.Windows.Forms;
namespace YourNamespace
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SetWindowPositionOnCurrentMonitor();
}
private void SetWindowPositionOnCurrentMonitor()
{
// Get the current working monitor
Screen currentScreen = Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle);
// Adjust the window's position to fit within the working area of the current monitor
double desiredLeft = currentScreen.WorkingArea.Left + 100; // Example: 100 pixels from the left
double desiredTop = currentScreen.WorkingArea.Top + 100; // Example: 100 pixels from the top
// Set the window's position
Left = desiredLeft;
Top = desiredTop;
}
}
}
In this example, the SetWindowPositionOnCurrentMonitor
method is called during the initialization of the MainWindow
to set the window's position on the current working monitor. Adjust the desiredLeft
and desiredTop
variables according to your desired position.
By using this approach, the WPF window will be displayed on the current working monitor in a multiple-monitor setup.