Search code examples
c#.netwindowspositiondimension

Save open application dimensions and positions on Windows to reopen them via configuration file?


Is there a way to open an application to a saved set of dimensions and positions (on Windows) via a script? I'd also like to, of course, save the dimensions and positions of open applications -- the other side of this script. Any suggestions? If a script can't get this done on a Windows machine is there a way with C#/.NET?


Solution

  • You can do this using a User32.dll call to SetWindowPos.

    For example:

        [DllImport("User32.dll")]
        public static extern IntPtr FindWindow(string className, string windowName);
    
        [DllImport("User32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr windowHandle, IntPtr parentWindowHandle, int x, int y, int width, int height, PositionFlags positionFlags);
    
        public static readonly IntPtr HWND_TOP = new IntPtr(0);
    
        [Flags]
        public enum PositionFlags : uint
        {
            ShowWindow = 0x40
        }
    
        static void Main(string[] args)
        {
            var windowHandle = FindWindow(null, "Untitled - Notepad");
            SetWindowPos(windowHandle, HWND_TOP, 0, 0, 640, 480, PositionFlags.ShowWindow);
        }
    

    This will find the window with the title "Untitled - Notepad", move it to 0, 0, and resize it to 640x480. I have added the bare minimal number of PositionFlags and HWND flags, look at the link I provided if you require more and add them in the same way :)

    Oh, and to read the dimensions out, take a look at GetWindowRect. Here's an example of how to use this from c#: Example.