简体   繁体   中英

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. I know PictureBox has a Name_Click method that is called when it's clicked, but I'm creating my pieces programatically, as follows:

    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.

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:

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:

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

or using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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