目次

フォームの表示位置を変更する - C#

プログラムのコードからフォームの表示位置を変更する方法を紹介します。

UI

下図のUIを準備します。実際に使用するボタンはbutton3, button4の2つです。


コード

以下のコードを記述します。コードはbutton3, button4のClickイベントを実装します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FormSizeAndPosition
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
      this.Location = new Point(100, 80);
    }

    private void button4_Click(object sender, EventArgs e)
    {
      this.Left = 200;
      this.Top = 64;
    }
  }
}

解説

button3のClickイベントではフォームのLocationプロパティに値を設定してフォームの表示位置を変更します。LocationプロパティにはPoint構造体(System.Drawing.Point)を代入します。
button4のClickイベントではフォームのLeft, Topプロパティに値を代入してフォームの表示位置を変更します。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


button3を押します。フォームの表示位置が(100, 80)に変わります。


button4を押します。フォームの表示位置が(200, 64)に変わります。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2012-05-14
iPentec all rights reserverd.