LoginSignup
3
5

More than 5 years have passed since last update.

C#のFormの位置と寸法

Posted at

image.png

C#のフォームをピッタリ並べたい。でもスキマが開く。なぜだ!!


FormのRectangle型のプロパティは5個くらいある。

用途によって使い分けるが、試しに2つの領域を書き重ねてみた。

image.png

オレンジがDesktopBounds、ライムがDisplayRectangleをRectangleToScreenで移動したもの。

DesktopBoundsでは影のエフェクトも含む領域となり、これを使って並べると隙間が開く。
RectangleToScreen(DisplayRectangle)ではタイトルバーを含めることができず、これを使って並べると一部が重なってしまう。


static class MyExt
{
    public static Rectangle hoge(this Form form)
    {
        Rectangle a = form.DesktopBounds;
        Rectangle b = form.RectangleToScreen(form.DisplayRectangle);

        return (new Rectangle(b.X, a.Y, b.Width, b.Y - a.Y + b.Height));
    }
}

こういう感じの計算で、それっぽい矩形を得られる。

image.png


こんな感じのコードを書くと

Form a = new Form()
{
    Text = "a",
    StartPosition = FormStartPosition.Manual,
    Location = Location + new Size(this.hoge().Width, 0),
};
a.Show();

Form b = new Form()
{
    Text = "b",
    StartPosition = FormStartPosition.Manual,
    Location = a.Location + new Size(a.hoge().Width, 0),
};
b.Show();

Form c = new Form()
{
    Text = "c",
    StartPosition = FormStartPosition.Manual,
    Location = b.Location + new Size(b.hoge().Width, 0),
};
c.Show();

Form d = new Form()
{
    Text = "d",
    StartPosition = FormStartPosition.Manual,
    Location = a.Location + new Size(0, a.hoge().Height),
};
d.Show();

Form e = new Form()
{
    Text = "e",
    StartPosition = FormStartPosition.Manual,
    Location = d.Location + new Size(d.hoge().Width, 0),
};
e.Show();

Form f = new Form()
{
    Text = "f",
    StartPosition = FormStartPosition.Manual,
    Location = e.Location + new Size(e.hoge().Width, 0),
};
f.Show();

いい感じに並べられる。

image.png

ただ、影で立体感が出てしまうので、そのあたりは好みが分かれるかも。
あと無理に並べると、画面解像度が足りない場合に飛び出るので注意。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5