ウインドウの位置を保存・復元する

プログラムを再度起動した時に前回のウインドウ位置やサイズを保存・復元する方法です。
保存する情報は
・ウインドウのサイズ(Width,Height)
・ウインドウの位置(Location)
・ウインドウの状態(最大化、最小化)
になります。

また、起動した時に画面からはみ出ている状態では困るのでそこも修正します。

ウインドウの情報を保存する

ウインドウのサイズ、位置、状態のやりとりはWinAPIを使用したほうが便利です。
画面外に吹っ飛ぶようなウインドウでも、画面内に収まるように自動で修正してくれます。

こんな感じのクラスを作って

public class WinAPI {
 // WinAPI
 // ウインドウ情報をセットする
 [DllImport("user32.dll")]
 public static extern bool SetWindowPlacement(
 	IntPtr hWnd,
 	[In] ref WINDOWPLACEMENT lpwndpl
 );
 //WinAPI
 // ウインドウ情報を取得する
 [DllImport("user32.dll")]
 public static extern bool GetWindowPlacement(
 	IntPtr hWnd,
 	out WINDOWPLACEMENT lpwndpl
 );
 
 // 以下 WinAPIで使用するクラス定義
 public struct WINDOWPLACEMENT {
 	public int length;
 	public int flags;
 	public SW showCmd;
 	public POINT minPosition;
 	public POINT maxPosition;
 	public RECT normalPosition;
 }
 
 [StructLayout(LayoutKind.Sequential)]
 public struct POINT {
 	public int X;
 	public int Y;
 
 	public POINT( int x, int y ) {
 		this.X = x;
 		this.Y = y;
 	}
 }
 
 [StructLayout(LayoutKind.Sequential)]
 public struct RECT {
 	public int Left;
 	public int Top;
 	public int Right;
 	public int Bottom;
 
 	public RECT( int left, int top, int right, int bottom ) {
 		this.Left = left;
 		this.Top = top;
 		this.Right = right;
 		this.Bottom = bottom;
 	}
 }
 
 public enum SW {
 	HIDE = 0,
 	SHOWNORMAL = 1,
 	SHOWMINIMIZED = 2,
 	SHOWMAXIMIZED = 3,
 	SHOWNOACTIVATE = 4,
 	SHOW = 5,
 	MINIMIZE = 6,
 	SHOWMINNOACTIVE = 7,
 	SHOWNA = 8,
 	RESTORE = 9,
 	SHOWDEFAULT = 10,
 }
}

こんな感じで使ってます。

public void ウインドウ情報の取得( Control c ) {
	WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
	WINAPI.GetWindowPlacement(c.Handle, out wp);
}

public void ウインドウ情報を設定( WINDOWPLACEMENT wp ) {
	if( wp.length != 0 ) {
		wp.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
		wp.flags = 0;
		wp.showCmd = ( wp.showCmd == SW.SHOWMINIMIZED ? SW.SHOWNORMAL : wp.showCmd );
		IntPtr hwnd = c.Handle;
		WinAPI.SetWindowPlacement(hwnd, ref wp);
	}
}


参考:http://grabacr.net/archives/1585