トップへ(mam-mam.net/)

指定モニターにアプリケーションウィンドウを移動させる ~Delphiでお手軽プログラミング

検索:

指定モニターにアプリケーションウィンドウを移動させる ~Delphiでお手軽プログラミング

プログラムの作成

Delphi IDEを起動し、「ファイル」⇒「Windows VCLアプリケーション -Delphi」をクリックします
今回は、フォーム上にボタンをプログラムから動的に作成しますので、 フォーム上にはコンポーネントを何も入れません。
以下ソースコードを記述します。
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private 宣言 }
    procedure onButtonClick(Sender:TObject);
  public
    { Public 宣言 }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var i:Integer;
    button:TButton;
begin
  for i := 0 to Screen.MonitorCount-1 do
  begin
    //コンストラクターCreateでAOwner:TComponent引数を与えられるものは、
    //破棄責任を、引数のコンポーネントに委ねることが出来る
    //ここでのSelfは自身のオブジェクト(Form1)のこと
    button:=TButton.Create(Self);
    //Self(Form1)ウィンドウに表示する
    button.Parent:=Self;
    button.Top:=i*50;
    button.Left:=4;
    button.Caption:=Format('モニター%dに表示',[(i+1)]);
    //ボタンのTagプロパティに、モニター番号を入れておく
    button.Tag:=i;
    button.Width:=200;
    //ボタンをクリックしたときに onButtonClick関数を呼び出す
    button.OnClick:=self.onButtonClick;
  end;
end;

procedure TForm1.onButtonClick(Sender: TObject);
var monitorNum:Integer;
begin
  //タグプロパティから、モニター番号を取得する
  monitorNum:=TButton(Sender).Tag;
  //Self(Form1)を指定モニター番号に移動する
  Self.MakeFullyVisible(Screen.monitors[monitorNum]);
end;

end.

実行する

複数のモニターがあるPCの場合は、その分、ボタンが動的に作成されます。
このフォームを移動したいモニターのボタンをクリックすると、このウィンドウ(フォーム)が移動します。
但し、位置(Left,Top)はお任せになります。 フォームに TPath をドラッグ&ドロップします。