0

MDI コンテナーであるフォームがあります。そのフォームで、それぞれにラベルが付いた 6 つの子フォームを生成します。

for (int i = 0; i < 6; i++)
{
    Form window = new Form();
    window.Width = 100;
    window.Height = 100;

    window.MdiParent = this;
    window.FormBorderStyle = FormBorderStyle.FixedToolWindow;

    Label label = new Label();
    label.AutoSize = true;
    label.Location = new System.Drawing.Point(1, 1);
    label.Size = new System.Drawing.Size(35, 13);
    label.TabIndex = 1;
    label.Name = "label" + i.ToString();
    label.Text = window.Top.ToString();

    window.LocationChanged += new System.EventHandler(HERE);

    window.Controls.Add(label);
    window.Show();              
}

窓用に変更した場所にイベントを追加しました。ラベルがウィンドウの位置に更新されるようにするにはどうすればよいでしょうか。

4

2 に答える 2

1

この行でうまくいくと思います:

window.LocationChanged += new EventHandler(delegate(object o, EventArgs evtArgs) { 
    label.Text = window.Location.ToString(); 
});
于 2009-05-31T19:50:55.003 に答える
0

ラムダ式または匿名メソッドを使用するのが最も簡単です。

window.LocationChanged += (sender, args) => label.Text = window.Top.ToString();

C# 1.1 を使用している場合は、ラベルが C# 2+ で自動的にキャプチャされるため、少し複雑にする必要があります。次のような新しいクラスを作成する必要があります。

internal class LocationChangeNotifier
{
    private readonly Label label;

    internal LocationChangeNotifier(Label label)
    {
        this.label = label;
    }

    internal void HandleLocationUpdate(object sender, EventArgs e)
    {
        label.Text = ((Control) sender).Top.ToString();
    }
}

次に、次のように使用します。

LocationChangeNotifier notifier = new LocationChangeNotifier(label);
window.LocationChanged += new EventHandler(notifier.HandleLocationUpdate);

キャプチャされた変数は素晴らしいものではありませんか? :)

于 2009-05-31T19:50:58.360 に答える