简体   繁体   English

如何获取Windows以引发以编程方式创建的PictureBox的mouseclick事件?

[英]How to get Windows for to raise mouseclick event for programatically created PictureBox?

I'm building a virtual board game, and I need to be able to click on the pieces to move them. 我正在构建一个虚拟棋盘游戏,我需要能够单击相应的棋子来移动它们。 The board is created as a picture in the background, and the pieces are pictureboxes over top of that. 木板在背景中被创建为图片,而碎片则是其上方的图片框。 More specifically, they are a custom class GamePiece that inherits from PictureBox. 更具体地说,它们是从PictureBox继承的自定义类GamePiece。 I know PictureBox has a Name_Click method that is called when it's clicked, but I'm creating my pieces programatically, as follows: 我知道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);
        }
    }

Therefore, I don't want to hardcode in methods to be called for each Gamepiece, because that would defeat my purpose here. 因此,我不想硬编码要为每个Gamepiece调用的方法,因为那样会违背我的目的。

Any suggestions? 有什么建议么? I can include any other code that would be helpful, and I'm pretty flexible as far as redesigning code, if that would make my life easier later. 我可以包括任何其他有用的代码,并且如果重新设计代码可以使以后的生活变得更轻松,则我非常灵活。 Thanks in advance. 提前致谢。

Just add Control.Click event handler for your control: 只需为您的控件添加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;
    }

on the Click event: Click事件上:

private void pieces_Click(object sender, EventArgs e)
{
    int id = (int) ((Pieces))sender.Tag;
    DoSomethingForId(id);
}

or using Anonymous Methods : 或使用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
                        };
    }
}

(Wire up to an event handler) (连接到事件处理程序)

Pieces[i].Click += new EventHandler(theOnClickEvent);

(The event handler) (事件处理程序)

void theOnClickEvent(object sender, EventArgs e)
    {
        //clicked.
    }

Could it be: 可能是:

gamePiece.Click += myEventHandler;

Where gamePiece is the GamePiece object, and myEventHandler is any form of event handler... delegate, lambda, whatever. 其中gamePieceGamePiece对象,而myEventHandler是任何形式的事件处理程序...委托,lambda等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM