如何获取Windows以引发以编程方式创建的PictureBox的mouseclick事件? [英] How to get Windows for to raise mouseclick event for programatically created PictureBox?

查看:106
本文介绍了如何获取Windows以引发以编程方式创建的PictureBox的mouseclick事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个虚拟棋盘游戏,我需要能够单击相应的棋子来移动它们.木板在背景中被创建为图片,而碎片则是其上方的图片框.更具体地说,它们是从PictureBox继承的自定义类GamePiece.我知道PictureBox有一个Name_Click方法,当单击它时会调用它,但是我正在以编程方式创建我的作品,如下所示:

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);
        }
    }

因此,我不想硬编码要为每个Gamepiece调用的方法,因为这样做会违背我的目的.

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;
    }

Click事件上:

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


或使用 Anonymous Methods :


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
                        };
    }
}

这篇关于如何获取Windows以引发以编程方式创建的PictureBox的mouseclick事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆