[英]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.