我有一段时间没有使用 C# 和 Visual Studio,所以我不记得在窗口设计器中是否有直接使用数组的方法,有人应该在评论中清除它;)。
但是您可能想要的是,而不是声明slider1,slider2,slider3,...您应该使用一个数组,以便您可以访问slider[0],slider[1],...
为此,您首先必须更改表单的设计以使用数组,然后在处理程序中访问该数组。
没有数组:
private System.Windows.Forms.TrackBar trackBar1;
private System.Windows.Forms.TrackBar trackBar2;
private System.Windows.Forms.TrackBar trackBar3;
[...]
this.trackBar1 = new System.Windows.Forms.TrackBar();
this.trackBar2 = new System.Windows.Forms.TrackBar();
this.trackBar3 = new System.Windows.Forms.TrackBar();
((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.trackBar3)).BeginInit();
this.SuspendLayout();
//
// trackBar1
//
this.trackBar1.Location = new System.Drawing.Point(154, 80);
this.trackBar1.Name = "trackBar1";
this.trackBar1.Size = new System.Drawing.Size(104, 45);
this.trackBar1.TabIndex = 0;
//
// trackBar2
//
this.trackBar2.Location = new System.Drawing.Point(154, 132);
this.trackBar2.Name = "trackBar2";
this.trackBar2.Size = new System.Drawing.Size(104, 45);
this.trackBar2.TabIndex = 1;
//
// trackBar3
//
this.trackBar3.Location = new System.Drawing.Point(154, 184);
this.trackBar3.Name = "trackBar3";
this.trackBar3.Size = new System.Drawing.Size(104, 45);
this.trackBar3.TabIndex = 2;
带数组:
private System.Windows.Forms.TrackBar[] trackBar = new System.Windows.Forms.TrackBar[3];
[...]
this.SuspendLayout();
for(int n = 0; n < 3; n++) {
this.trackBar[n] = new System.Windows.Forms.TrackBar();
((System.ComponentModel.ISupportInitialize)(this.trackBar[n])).BeginInit();
this.trackBar[n].Location = new System.Drawing.Point(154, 80 + n*52);
this.trackBar[n].Name = "trackBar[" + n + "]";
this.trackBar[n].Size = new System.Drawing.Size(104, 45);
this.trackBar[n].TabIndex = 0;
}
然后您可以通过 trackBar[x] 访问所有轨迹栏。您可以将声明和 for 循环中的 3 更改为您想要的常量或变量。