static void Window_LocationChanged(object sender, EventArgs e) { Window win = (Window)sender; var info = Monitors.GetMonitorFromWindow(win, NotFoundOptions.DefaultToNearest); if (win.MaxWidth != info.WorkingArea.Width || win.MaxHeight != info.WorkingArea.Height) { if (win.MaxWidth != double.PositiveInfinity && win.MaxHeight != double.PositiveInfinity) { SetJustChangedMonitor(win, DateTime.Now); } win.MaxWidth = info.WorkingArea.Width; win.MaxHeight = info.WorkingArea.Height; } }
static void Window_SizeChanged(object sender, SizeChangedEventArgs e) { Window win = (Window)sender; if (win.SizeToContent != SizeToContent.WidthAndHeight) { return; } if (!GetCenterOnSizedToContent(win)) { return; } var dt = GetJustChangedMonitor(win); if (dt.HasValue) { if (dt.Value.Add(TimeSpan.FromSeconds(1)) < DateTime.Now) { SetJustChangedMonitor(win, null); } else { return; } } var info = Monitors.GetMonitorFromWindow(win, NotFoundOptions.DefaultToNearest); if (info.WorkingArea.Contains(new Rect(win.Left, win.Top, e.NewSize.Width, e.NewSize.Height))) { return; } win.Left = info.WorkingArea.Left + (info.WorkingArea.Width / 2) - (e.NewSize.Width / 2); win.Top = info.WorkingArea.Top + (info.WorkingArea.Height / 2) - (e.NewSize.Height / 2); }