我正在制作 N*M 大小的数独游戏。每个数字都在一个按钮上。 当程序启动时,所有按钮都是空的,我想如果我点击一个按钮,它会在上面制作一个小面板,每个数字都有按钮可供选择。
private void adatB_Click(object sender, EventArgs e)
{
Button button = sender as Button;
int[] hely = button.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray();
Panel szamok = new Panel
{
Location = MousePosition,
Size = new Size(100, 100)
};
Controls.Add(szamok);
TableLayoutPanel minitabla = new TableLayoutPanel
{
Dock = DockStyle.Fill,
ColumnCount = szorzat,
RowCount = szorzat,
};
for (int i = 0; i < szorzat; i++)
{
minitabla.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
minitabla.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
}
szamok.Controls.Add(minitabla);
Button[,] szamokB = new Button[meret[0], meret[1]];
int d = 1;
for (int i = 0; i < meret[0]; i++)
{
for (int j = 0; j < meret[1]; j++)
{
szamokB[i, j] = new Button();
szamokB[i, j].Tag= hely[0]+","+hely[1];
szamokB[i, j].Text = d.ToString();
szamokB[i, j].Dock = DockStyle.Fill;
szamokB[i, j].Click += szamokB_Click;
minitabla.Controls.Add(szamokB[i, j], i, j);
d++;
}
}
}
private void szamokB_Click(object sender, EventArgs e)
{
Button button = sender as Button;
int[] hely = button.Tag.ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray();
adatB[hely[0], hely[1]].Text = button.Text;
}
当我单击按钮时出现的问题是未创建 Pane 。 meret[0] 变量是 N,meret[1] 是 M,adatB 是标签中位置的按钮数组。 如果我选择了数字,我该如何关闭该面板?
最佳答案
首先,你应该正确计算出mouseposition。
来自 MSDN:
Gets the position of the mouse cursor in screen coordinates.
你应该使用这样的东西:
Location = new Point(MousePosition.X - this.Location.X, MousePosition.Y - this.Location.Y)
你可能需要这个,把你的面板放在前面:
Controls.Add(szamok);
szamok.BringToFront();
要关闭面板,您可以存储选择器面板,稍后可以将其从控件中删除,使用如下内容:
public partial class Form1 : Form
{
private Panel myPanel = null;
private void adatB_Click(object sender, EventArgs e)
{
...
Panel szamok = new Panel
{
Location = new Point(MousePosition.X - this.Location.X, MousePosition.Y - this.Location.Y),
Size = new Size(100, 100)
};
if (this.myPanel != null)
{
this.Controls.Remove(this.myPanel);
}
this.myPanel = szamok;
Controls.Add(szamok);
szamok.BringToFront();
...
}
private void szamokB_Click(object sender, EventArgs e)
{
if (this.myPanel != null)
{
this.Controls.Remove(this.myPanel);
this.myPanel = null;
}
...
}
}
关于c# 鼠标动态面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573148/