1

I wrote a simple C# program that saves the locations and sizes of open windows to a file, and then can also restore them from that file (based on command-line arguments). This always works for some programs and not for others, and I don't know why.

The part that gets window position (x,y) and size (w,h) uses this standard Windows function

WINDOWPLACEMENT placement = GetWindowPlacement(windowCaption);

The part that sets a window's size and position uses this standard Windows function

SetWindowPos(target_hwnd, IntPtr.Zero, wi.x, wi.y, wi.w, wi.h, 0);

These are declared in the code like so

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetWindowPos(IntPtr hWnd,
    IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SetWindowPosFlags uFlags);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);

The rest of the code is unremarkable: save some data to a text file, read some data from a text file. All of it is copy-pasted from online examples, and I am a novice C# / Windows programmer.

The program works quite well on certain programs and not at all on others. I can restore Chrome to its size and position, but not Firefox, and not Microsoft Edge. Visual Studio Code works, but not R Studio. This is a surprise to me, because (not knowing much about Windows programming) I expected that the GUI part of any Windows program was coded with standard Windows libraries, and so any program that works on Windows would respond to SetWindowPos the same way.

Why does this work for some programs and not for others?

I need to do this because I have a 4K monitor, and somehow Windows loses the size and position of most windows every time the monitor is turned off or times out. I posted separately about this, got no solution, so I wrote my own, which mostly works. https://superuser.com/questions/1513288/windows-loses-window-position-on-large-monitor

If anyone is interested, the source code is at https://github.com/radumanolescu/WinPos

Running Windows 10 Pro, fully patched, on a 2019 PC with solid specs.

radumanolescu
  • 3,607
  • 1
  • 20
  • 30

0 Answers0