传递winforms面板的网格坐标

本文关键字:网格 坐标 winforms 传递 | 更新日期: 2023-09-27 18:09:00

如果我在一个10 x 10的网格中有一个面板数组,并且我用x和y坐标描述每个面板的位置,我如何将其传递给面板。单击事件吗?

int sqSize = 80;
int bAcross = 10;
CPanels = new Panel[bAcross, bAcross]; //10 * 10 grid
    for (int y = 0; y < bAcross; y++)
    {
        for (int x = 0; x < bAcross; x++)
        {
            var newPan = new Panel
            {
                Size = new Size(sqSize, sqSize),
                Location = new Point(x * sqSize, y * sqSize)
            };
            Controls.Add(newPan);
            CPanels[x, y] = newPan; //add to correct location on grid
            newPan.Click += Pan_Click;

在click事件中我需要做什么呢?

private void Pan_Click(object sender, EventArgs e)
{
    int x = (extract x coord)
    int y = (extract y coord)
}
编辑:澄清我正在寻找网格中的位置。基本上,网格的左上角应该是0,0右下角应该是10,10

传递winforms面板的网格坐标

触发Pan_Click事件的Panelsender参数中可用:

private void Pan_Click(object sender, EventArgs e)
{
    var panel = sender as Panel;
    if (panel == null)
        return;
    int x = panel.Location.X;
    int y = panel.Location.Y;
}

因为你实际上想要的是Panel相对于10x10网格的位置,并且因为你通过将sqSize乘以网格中的当前位置来设置每个Panel的位置:

Location = new Point(x * sqSize, y * sqSize)

您可以简单地将每个坐标再次除以sqSize,以获得原始的xy值:

private void Pan_Click(object sender, EventArgs e)
{
    var panel = sender as Panel;
    if (panel == null)
        return;
    int x = panel.Location.X / sqSize;
    int y = panel.Location.Y / sqSize;
}

(另外请注意,如果它是一个10x10的网格,右下角将是9,9而不是10,10)