我正在使用简单的代码生成一个网格(gridSize * gridSize字段,其中的行将它们分为列和行,基本上是TicTacToe网格)。
由于我在Form_Load期间动态创建面板,我还需要调整表单的大小。但是,将它设置为gridSize * tileSize,gridSize * tileSize还不够大 - 我通过实验发现,我需要为gridSize = 3和tileSize = 120添加~15到宽度和~40到高度。为什么会这样?
以下代码:
private void Form1_Load(object sender, EventArgs e)
{
const int tileSize = 120;
const int gridSize = 3;
/* Here: When setting size, I need to add 15 and 40? */
this.Size = new System.Drawing.Size(tileSize * gridSize + 15, tileSize * gridSize + 40);
// initialize the "board"
tictactoeFields = new Panel[gridSize, gridSize]; // column, row
// double for loop to handle all rows and columns
for (var n = 0; n < gridSize; n++)
{
for (var m = 0; m < gridSize; m++)
{
// create new Panel control which will be one
// tic tac toe field
var newPanel = new Panel
{
Size = new Size(tileSize, tileSize),
Location = new Point(tileSize * n, tileSize * m)
};
// add to our 2d array of panels for future use
tictactoeFields[n, m] = newPanel;
newPanel.BackColor = Color.White;
if(n != 0)
{
// Draw a line in front (to the left) of this panel
Panel leftSeparator = new Panel
{
Size = new Size(1, tileSize),
Location = newPanel.Location,
BackColor = Color.Black
};
Controls.Add(leftSeparator);
}
if(m != 0)
{
// Draw a line on top (above) this panel
Panel topSeparator = new Panel
{
Size = new Size(tileSize, 1),
Location = newPanel.Location,
BackColor = Color.Black
};
Controls.Add(topSeparator);
}
}
}
foreach(Panel pan in tictactoeFields)
{
// add to Form's Controls so that they show up
Controls.Add(pan);
}
}
答案 0 :(得分:1)
Size
属性只是设置Bounds属性大小的简写,其中包括非客户端元素,如滚动条,边框,标题栏和菜单。
您应该做的是设置ClientRectangle属性的大小,或使用ClientSize
简写。
还有一个DisplayRectangle属性,其中包含填充,但在这种情况下使用ClientRectangle
属性。
this.ClientSize = new Size((tileSize * gridSize), (tileSize * gridSize));