Jac*_*ack 6 .net c# 2d winforms
我应该使用Windows Forms Application在2D中创建一个魔术方块.它应该如下所示:
但是,用户应该能够决定正方形的大小(3x3,5x5,7x7等).我已经在控制台应用程序中编写了代码,但我不知道如何添加2D图形.
有人已经问过这个问题(如何将我的结果放入GUI?),其中一个答案是使用DataGridView
,但我不确定这是否是我正在寻找的,因为我无法让它看起来喜欢这张照片.
任何想法或建议?
您可以TableLayoutPanel
动态地使用a 和向面板添加按钮.
如果您不需要与按钮交互,则可以添加Label
.
动态创建方块:
public void CreateSquare(int size)
{
//Remove previously created controls and free resources
foreach (Control item in this.Controls)
{
this.Controls.Remove(item);
item.Dispose();
}
//Create TableLayoutPanel
var panel = new TableLayoutPanel();
panel.RowCount = size;
panel.ColumnCount = size;
panel.BackColor = Color.Black;
//Set the equal size for columns and rows
for (int i = 0; i < size; i++)
{
var percent = 100f / (float)size;
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent));
panel.RowStyles.Add(new RowStyle(SizeType.Percent, percent));
}
//Add buttons, if you have your desired output in an array
//you can set the text of buttons from your array
for (var i = 0; i < size; i++)
{
for (var j = 0; j < size; j++)
{
var button = new Button();
button.BackColor = Color.Lime;
button.Font = new Font(button.Font.FontFamily, 20, FontStyle.Bold);
button.FlatStyle = FlatStyle.Flat;
//you can set the text of buttons from your array
//For example button.Text = array[i,j].ToString();
button.Text = string.Format("{0}", (i) * size + j + 1);
button.Name = string.Format("Button{0}", button.Text);
button.Dock = DockStyle.Fill;
//If you need interaction with buttons
button.Click += b_Click;
panel.Controls.Add(button, j, i);
}
}
panel.Dock = DockStyle.Fill;
this.Controls.Add(panel);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要与按钮交互
void button_Click(object sender, EventArgs e)
{
var button = (Button)sender;
//Instead put your logic here
MessageBox.Show(string.Format("You clicked {0}", button.Text));
}
Run Code Online (Sandbox Code Playgroud)
举个例子,你可以打电话
CreateSquare(3);
Run Code Online (Sandbox Code Playgroud)
截图: