【发布时间】:2017-01-26 08:36:54
【问题描述】:
我目前正在尝试在 Visual Studio 社区中创建一个名为 GameButton 的新类。我试图将所有代码放入其中,以便所有代码都是从按钮而不是表单生成的,但是现在我移动了大部分代码,它要么不显示,要么进入无限循环,并且我目前不知道如何修复它。如果我没有提供足够的信息,我会在需要时提供更多信息。
(Speelveld 是表单内部的一个表单,用于确定按钮的位置。“speelveld”是从 Visual Studio 的内置工具箱中导入的面板。然后代码引用该表单来构建按钮。 )
窗体c#
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Marble();
}
public void Marble()
{
string line;
System.IO.StreamReader file = new System.IO.StreamReader("Bitmap.txt");
int ButtonHeight = 40;
int y_row = 0;
GameButton testButton = new GameButton();
while ((line = file.ReadLine()) != null)
{
for (int x_row = 0; x_row < line.Count(); x_row++)
{
if(line.Substring(x_row, 1) == "1")
{
Speelveld.BackColor = Color.White;
BackColor = Color.White;
testButton.Currentcolor = false;
if (x_row == 4 && y_row == 6)
{
testButton.BackColor = Color.White;
}
else
{
Speelveld.Controls.Add(testButton);
}
}
}
y_row++;
}
}
}
}
GameButton c#
namespace WindowsFormsApplication9
{
public class GameButton: Button
{
public int Row { get; set; }
public int Column { get; set; }
public bool Currentcolor { get; set; }
Pen myPen;
public int ButtonHeight = 40;
public int y_row = 0;
public int x_row = 0;
public void Startup()
{
this.BackColor = Color.Red;
this.Height = ButtonHeight;
this.Width = ButtonHeight;
this.Top = y_row * ButtonHeight + 20;
this.Left = x_row * ButtonHeight + 20;
this.Text = "X: " + x_row.ToString() + " Y: " + y_row.ToString();
this.MouseUp += TmpButton_MouseUp;
}
protected override void OnPaint(PaintEventArgs pevent)
{
int radius = 20;
pevent.Graphics.Clear(Color.White);
Graphics graphics = pevent.Graphics;
myPen = new Pen(new SolidBrush(this.BackColor), 2f);
pevent.Graphics.FillEllipse(new SolidBrush(this.BackColor), 20 - radius, 20 - radius,
radius + radius, radius + radius);
myPen.Dispose();
}
private void TmpButton_MouseUp(object sender, MouseEventArgs e)
{
GameButton Mygamebutton = (GameButton)sender;
Mygamebutton.Currentcolor = !Mygamebutton.Currentcolor;
if (Mygamebutton.Currentcolor == true)
{
Mygamebutton.BackColor = Color.Black;
}
else
{
Mygamebutton.BackColor = Color.White;
}
}
}
}
位图.txt
011111110
111111111
111111111
011111110
001111100
000111000
000010000
【问题讨论】:
-
bitmap.txt 是什么样子的?
-
它是二进制的,0和1,我把它添加到帖子中。
-
我在您的代码中看不到任何可能导致无限循环的内容。尝试一步步调试它,看看发生了什么。
-
好的,您的问题是因为您的
OnPaint覆盖。把它注释掉,你会看到按钮 -
这不是问题,他只是重写了 OnPaint 来自定义绘制他的按钮。