2013年1月15日火曜日

WPF Windowのクライアントサイズ設定方法

WPFにおけるウィンドウのクライアント領域サイズの設定方法メモ。

1. 簡単な方法

①Windowコントロールのプロパティの[SizeToContent]を[WidthAndHeight]に設定。

②Windowコントロール内の[Grid]コントロールの[Width]と[Height]を設定。

2. 面倒な方法

以下の様にSystemParametersを使用して自力でクライアントサイズを計算。

/// <summary>
/// ウィンドウのクライアントサイズを設定
/// </summary>
/// <param name="w"></param>
/// <param name="h"></param>
private void SetWindowSize(int w, int h)
{
var borderWidth = SystemParameters.ResizeFrameVerticalBorderWidth;
var borderHeight = SystemParameters.ResizeFrameHorizontalBorderHeight;
var captionHeight = SystemParameters.CaptionHeight;
this.Width = w + borderWidth + borderWidth;
this.Height = h + borderHeight + borderHeight + captionHeight;
}
view raw gistfile1.cs hosted with ❤ by GitHub
3. 更に面倒な方法

①Win32APIのGetClientRectでクライアント領域サイズを取得する。

using System;
using System.Security;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
namespace Win32
{
public class GetClientRect
{
[DllImport("user32.dll",EntryPoint="GetClientRect")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _GetClientRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
/// <summary>
/// クライアント領域サイズ取得
/// </summary>
/// <param name="visual"></param>
/// <returns></returns>
public static Rect Get(Visual visual)
{
HwndSource source = (HwndSource)HwndSource.FromVisual(visual);
RECT r;
if (_GetClientRect(source.Handle, out r))
{
return new Rect(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);
}
return Rect.Empty;
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
②フォームロード時にウィンドウサイズをクライアントサイズに置き換える。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
// クライアント領域調整
Rect r = Win32.GetClientRect.Get(this);
Width = Width + Width - r.Width;
Height = Height + Height - r.Height;
}
view raw gistfile1.cs hosted with ❤ by GitHub

0 件のコメント:

コメントを投稿