I have an application with at least 2 separate windows.
The secondary window is too far from the PC to use the mouse, so I have a method that temporarily brings that specific window to the current main display, changes are done, then the window is sent back.
This worked well under Windows 10, however under Windows 11, the window seems to disappear and is nowhere to be seen during the initial call. It can however be sent back (from wherever it was hiding) to the secondary monitor.
Here is some code to position the window (normal MoveWindow):
// Position is assigned in the constructor of the second window
public System.Drawing.Rectangle Position { get; set; }
[DllImport("user32.dll", SetLastError = true)]
private static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
MoveW();
}
public void MoveW()
{
WindowInteropHelper wih = new(this);
IntPtr hWnd = wih.Handle;
if (!Position.IsEmpty)
{
_ = MoveWindow(hWnd, Position.Left, Position.Top, Position.Width, Position.Height, false);
}
}
and here is how I am bringing the window to the current display (work perfect Win10):
// Getting the coordinates of the MainWindow
var screen = System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(App.Current.MainWindow).Handle);
System.Drawing.Rectangle rect = screen.WorkingArea;
// Simply passing them to second window needing to be moved
if (!rect.IsEmpty)
{
var wih = new WindowInteropHelper(this);
IntPtr hWnd = wih.Handle;
MoveWindow(hWnd, rect.Left, rect.Top, rect.Width, rect.Height, false);
}
Here is the link for MoveWindow
I have created a small GitHub project to illustrate the issue. If you have 2 screens and win10 and 11, get it from here.
Any suggestions?
CodePudding user response:
As far as I noticed, on Windows 11, WindowState.Maximized seems to prevent the window from being shown after its location is changed by MoveWindow function.
So the workround is returing to WindowState.Normal before calling MoveWindow. It would be something like below.
WindowState state = this.WindowState;
try
{
this.WindowState = WindowState.Normal;
MoveWindow(hWnd, rect.Left, rect.Top, rect.Width, rect.Height, false);
}
finally
{
this.WindowState = state;
}