コントロールをコンテナの後ろに送りたいと思います。他のいくつかのコントロールが作成され、同じコンテナーから削除されても、このコントロールの位置が失われることは望ましくありません。
これを達成するためのより良い方法はありません:
// Force this control to stay back
private void panel1_ControlAdded(object sender, ControlEventArgs e)
{
pictureBox1.SendToBack();
}
私にはやり過ぎに見えます。これを達成するためのより良い方法はありますか?
編集:
controls.add はデフォルトでコントロールを前に置くと言われています。この動作を再現できないか、どこかでポイントを見逃しています。これが私が試したものです:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
System.Windows.Forms.Button button1;
public Form1() { InitializeComponent(); }
void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(225, 182);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(139, 39);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pictureBox1
//
this.pictureBox1.Image = global::WindowsFormsApplication4.Properties.Resources.Tulips;
this.pictureBox1.Location = new System.Drawing.Point(36, 26);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(299, 175);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(376, 233);
this.Controls.Add(this.button1);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
private PictureBox pictureBox1;
Point xy;
// Add a button or anything else
private void button1_Click(object sender, EventArgs e)
{
var ctl = new Button();
ctl.Location = xy;
this.Controls.Add(ctl);
xy.Offset(10, 10);
}
// First of all, send the picture box to back
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.SendToBack();
}
}
}
お気づきのように、button1 を数回押すと、新しく追加されたボタン (テキスト ボックスに置き換えることができます...) は、Load イベントで送信されたピクチャ ボックスの後ろに移動します。したがって、Control.Add の想定されるデフォルトの動作に頼ることは絶対にできません。