【问题标题】:How to detect when a window has been dragged to another monitor in a WPF application?如何检测窗口何时被拖到 WPF 应用程序中的另一个监视器?
【发布时间】:2021-01-08 03:45:47
【问题描述】:

我试图检测我的 WPF 应用程序的窗口何时在监视器之间拖动,因此我可以更改其大小以适应它被拖动到的监视器。我尝试了以下方法:

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

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

但是,当我将窗口移动到另一个监视器时,SystemEvents_DisplaySettingsChanged 永远不会被调用。

另外,我不知道这是否是保持应用程序大小响应的最佳方式。

【问题讨论】:

    标签: c# wpf window


    【解决方案1】:

    您可以在窗口的构造函数中设置LocationChanged 的事件处理程序:

    this.LocationChanged += MainWindow_LocationChanged;
    

    并检查事件处理程序中的监视器:

    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
    }
    

    【讨论】:

    • LocationChanged 在您移动窗口时引发。也许如果应用程序可以检测到移动的结束会更好。我没有在 WPF 中找到任何合适的事件。 WPF 的 System.Windows.Forms 有什么替代品吗?
    • @user2250152 恐怕WPF中没有其他选择,至少我不知道。答案是如何做到这一点。 OP 可以根据需要调整/调整它。
    猜你喜欢
    • 2010-10-25
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    相关资源
    最近更新 更多