[英]How to get Windows for to raise mouseclick event for programatically created PictureBox?
我正在构建一个虚拟棋盘游戏,我需要能够单击相应的棋子来移动它们。 木板在背景中被创建为图片,而碎片则是其上方的图片框。 更具体地说,它们是从PictureBox继承的自定义类GamePiece。 我知道PictureBox有一个Name_Click方法,当单击它时会调用它,但是我正在以编程方式创建我的作品,如下所示:
public Player(int identity, GameBoard Board)
{
ID = identity;
for (int i = 0; i < 4; i++)
{
Pieces[i] = new GamePiece(ID, Board.GetPlaceSize(), Board.GetPieceColor(ID), Board);
}
}
因此,我不想硬编码要为每个Gamepiece调用的方法,因为那样会违背我的目的。
有什么建议么? 我可以包括任何其他有用的代码,并且如果重新设计代码可以使以后的生活变得更轻松,则我非常灵活。 提前致谢。
只需为您的控件添加Control.Click
事件处理程序即可:
public Player(int identity, GameBoard Board)
{
ID = identity;
for (int i = 0; i < 4; i++)
{
Pieces[i] = new GamePiece(ID, Board.GetPlaceSize(), Board.GetPieceColor(ID), Board);
Pieces[i].Tag = ID;
Pieces[i].Click += pieces_Click;
}
在Click
事件上:
private void pieces_Click(object sender, EventArgs e)
{
int id = (int) ((Pieces))sender.Tag;
DoSomethingForId(id);
}
或使用Anonymous Methods
:
public Player(int identity, GameBoard Board)
{
ID = identity;
for (int i = 0; i < 4; i++)
{
Pieces[i] = new ....
Pieces[i].Click += (sender, e) =>
{
// Do some thing
};
}
}
(连接到事件处理程序)
Pieces[i].Click += new EventHandler(theOnClickEvent);
(事件处理程序)
void theOnClickEvent(object sender, EventArgs e)
{
//clicked.
}
可能是:
gamePiece.Click += myEventHandler;
其中gamePiece
是GamePiece
对象,而myEventHandler
是任何形式的事件处理程序...委托,lambda等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.