将MultipleMonitor应用程序从WinForms转换为WPF

本文关键字:转换 WPF WinForms MultipleMonitor 应用程序 | 更新日期: 2023-09-27 18:25:48

我遇到了一个小问题,现在试着解决了将近6到8个小时,但我没有找到任何匹配的答案。我是WPF的新手,所以请指出我犯的任何错误。

起初,我在App.xaml.cs中有以下内容:

namespace WpfVideowand
{
  public partial class App : Application
  {
    ...
    private void Application_Startup(object sender, StartupEventArgs e)
    {
      foreach (System.Windows.Forms.Screen MyScreen in System.Windows.Forms.Screen.AllScreens)
      {
        List<string> MyStrings = Xml.GetScreens(i);
        if (MyStrings[1] == "true")
        {
          OpenWindow(MyScreen, MyStrings[0], i);
        }
        i++;
        Shelf MyShelf = new Shelf(MyScreen, i, MyStrings[0]);
        MyShelf.Show();
      }
    }
    private void OpenWindow(System.Windows.Forms.Screen myScreen, string configName, int screenNumber)
    {
      Shelf NewShelf = new Shelf(myScreen, screenNumber, configName);
    }
  }
}

在Shelf.xaml.cs中,它看起来是这样的:

namespace WpfVideowand
{
  public partial class Shelf : Window
  {
    [DllImport("user32.dll")]
    static extern IntPtr GetActiveWindow();
    System.Windows.Forms.Screen _Screen { get; set; }
    ...
    public Shelf(System.Windows.Forms.Screen myScreen, int screenNumber, string configName)
    {
      InitializeComponent();
      _Screen = myScreen;
      ShowOnMonitor(screenNumber);
      ...
    }
    private void ShowOnMonitor(int screenNumber)
    {
      System.Windows.Forms.Screen[] ScreenArray;
      ScreenArray = System.Windows.Forms.Screen.AllScreens;
      int XCoord = Convert.ToInt32(ScreenArray[screenNumber].Bounds.Left);
      this.Left = XCoord;
      int YCoord = Convert.ToInt32(ScreenArray[screenNumber].Bounds.Top);
      this.Top = XCoord;
      IntPtr active = GetActiveWindow();
      System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(window => new WindowInteropHelper(window).Handle == active).Name = "Monitor" + screenNumber.ToString();
      System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(window => new WindowInteropHelper(window).Handle == active).WindowState = WindowState.Maximized;
    }
    ...
  }
}

上面描述的方法在Windows窗体应用程序中运行良好。在WPF中,我遇到了一个问题,即我得到了错误消息,该矩形(窗口)将没有Top或Left属性。

我甚至用其他方式尝试过,比如用创建

System.Windows.Forms.Screen _screen = System.Windows.Forms.Screen.FromControl(this);

一个对象,该对象将具有.Top和.Left。但我收到消息,我无法将Shelf对象转换为System.Windows.Forms.Control。有人建议我如何让我的屏幕出现在显示器上应该有的地方吗?

将MultipleMonitor应用程序从WinForms转换为WPF

好吧,我自己找到了。。。对于任何有兴趣在这里找到这个问题的答案的人来说,它是:首先,请确保实现了正确的引用。为此,您需要System.Drawing和System.Windows.Forms然后看到你用Startup="Application_Startup"之类的东西启动应用程序,而不是uri,因为你想启动许多表单,而不是一个。之后绝对要确保不要在XAML中将Windows样式设置为最大化(这确实花了我将近4个小时。在这期间,我长了56根白发)。在"代码隐藏"中使用此选项:System.Windows.Application.Current.Windows.OfType().SingleOrDefault(window=>new WindowInteropHelper(window).Handle==活动).WindowState=WindowState.Maximized;