Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

c# - How to detect when a window has been dragged to another monitor in a WPF application?

I am trying to detect when the window of my WPF application is dragged between monitors, so I can change its size to fit the monitor it has been dragged to. I tried the following:

private void Application_Startup(object sender, StartupEventArgs e)
{
        SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
}

public void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
        Console.WriteLine("Changed");
}

However the SystemEvents_DisplaySettingsChanged never gets called when I move the window to another monitor.

Also, I don't know if this is the best way to keep my application's sizes responsive.

question from:https://stackoverflow.com/questions/65623175/how-to-detect-when-a-window-has-been-dragged-to-another-monitor-in-a-wpf-applica

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set in constructor of your window an event handler for LocationChanged:

this.LocationChanged += MainWindow_LocationChanged;

And check the monitor in the event handler:

private void MainWindow_LocationChanged(object sender, EventArgs e)
{
    System.Windows.Forms.Screen screen = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle);
    //evaluate the screen variable
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...