2 回答
TA贡献1793条经验 获得超6个赞
更改NOT为List<PictureBox>.
然后,在方法中添加一个new PictureBox实例。请注意,需要更改以获取参数。NOTspawnGate()Drag()PictureBox
编辑:根据评论中的要求,为了访问此问题的其他人的利益,这里正是需要更改代码才能获得 OP 请求的行为的方法。请注意,此设计可以而且应该在几个方面进行重构。
List<PictureBox> NOT = new List<PictureBox>();
Point startPoint = new Point();
public Form1()
{
InitializeComponent();
Drag();
}
private void button1_Click(object sender, EventArgs e)
{
spawnGate();
}
public void spawnGate()
{
var pictureBox = new PictureBox()
{
Width = 100,
Height = 50,
Image = Properties.Resources.Not_gate,
SizeMode = PictureBoxSizeMode.Zoom
}
Drag(pictureBox);
NOT.Add(pictureBox);
workspace.Controls.Add(pictureBox);
}
public void Drag(PictureBox pictureBox)
{
pictureBox.MouseDown += (ss, ee) =>
{
if (ee.Button == System.Windows.Forms.MouseButtons.Left)
startPoint = Control.MousePosition;
};
pictureBox.MouseMove += (ss, ee) =>
{
if (ee.Button == System.Windows.Forms.MouseButtons.Left)
{
Point temp = Control.MousePosition;
Point res = new Point(startPoint.X - temp.X, startPoint.Y - temp.Y);
pictureBox.Location = new Point(pictureBox.Location.X - pictureBox.X, pictureBox.Location.Y - res.Y);
startPoint = temp;
}
};
}
TA贡献1943条经验 获得超7个赞
您不必直接在表单上保存指向 NOT 的指针(或者,如果您以后需要调用它们,可以将它们保存到列表中)。
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
spawnGate("not");
}
// This list is optional, if you easily want to find them later
List<PictureBox> allNOTs = new List<PictureBox>();
public void spawnGate(string type)
{
switch (type)
{
case "not":
PictureBox NOT = new PictureBox();
NOT.Width = 100;
NOT.Height = 50;
NOT.Image = Properties.Resources.Not_gate;
NOT.SizeMode = PictureBoxSizeMode.Zoom;
NOT.MouseDown += (ss, ee) =>
{
// Mouse down event code here
};
NOT.MouseMove += (ss, ee) =>
{
// Mouse move event code here
};
allNOTS.Add(NOT); // Optional if you easily want to find it later
workspace.Controls.Add(NOT);
break;
}
}
}
- 2 回答
- 0 关注
- 229 浏览
添加回答
举报