[英]My MessageBox.Show Code In C# Isn't Working. There Are No Errors But Something Is Wrong
所以我最近一直在努力学习C#,所以我想我会试试像Tic-Tac-Toe这样简单的项目。 我目前正在尝试添加点击功能,以确保它正常工作我放入一个MessageBox.Show以确保它新的哪个区域我点击。 但是,当我运行它时没有出现任何错误,但是当我点击一个盒子时没有发生任何事情。 有谁知道我的代码有什么问题? 它是MessageBox.Show代码或其他东西的问题? 这是我的代码:
在Board.cs文件中,我有:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class Board
{
private Rectangle[,] slots = new Rectangle[3, 3];
private Holder[,] holders = new Holder[3, 3];
public const int X = 0;
public const int O = 1;
public const int B = 2;
public void initBoard()
{
for (int x = 0; x < 3; x++)
{
for (int y = 0; y < 3; y++)
{
slots[x, y] = new Rectangle(x * 167, y * 167, 167, 167);
holders[x, y] = new Holder();
holders[x, y].setValue(B);
holders[x, y].setLocation(new Point(x, y));
}
}
}
public void detectHit(Point loc)
{
int x = 0;
int y = 0;
if (loc.X < 167)
{
x = 0;
}
else if (loc.X > 167 && loc.X < 334)
{
x = 1;
}
else if (loc.X > 334)
{
x = 2;
}
if (loc.Y < 167)
{
y = 0;
}
else if (loc.Y > 167 && loc.Y < 334)
{
y = 1;
}
else if (loc.Y > 334 && loc.Y < 500)
{
y = 2;
}
MessageBox.Show(x.ToString() + ", " + y.ToString() + "/n/n" + loc.ToString());
}
}
class Holder
{
private Point location;
private int value = Board.B;
public void setLocation(Point p)
{
location = p;
}
public Point getLocation()
{
return location;
}
public void setValue(int i)
{
value = i;
}
public int getValue()
{
return value;
}
}
}
然后在我的Form1.cs文件中,我有:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
GFX engine;
Board theBoard;
public Form1()
{
InitializeComponent();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Graphics toPass = panel1.CreateGraphics();
engine = new GFX(toPass);
theBoard = new Board();
theBoard.initBoard();
}
private void Form1_Click(object sender, EventArgs e)
{
Point mouse = Cursor.Position;
mouse = panel1.PointToClient(mouse);
theBoard.detectHit(mouse);
}
}
}
根据事件处理程序的名称(Form1_Click),我怀疑你已经将click事件处理程序连接到表单的click事件而不是panel1的click事件。 请注意,如果用户单击表单内的面板,则只会触发面板的单击事件,而不会触发表单。
您可能没有注册该活动。 尝试在构造函数中注册它:
public Form1()
{
InitializeComponent();
//Register click event with handler
this.Click += new EventHandler(Form1_Click);
}
任何有意义的唯一解释是Form1_Click
没有运行。 如果它被执行,那么detectHit
肯定会运行。 肯定会调用MessageBox.Show
。 没有执行分支可以避免显示MessageBox.Show
。 在Form1_Click
执行的情况下不调用MessageBox.Show
的唯一可能方法是引发异常。 在这种情况下你会注意到这一点。
事件处理程序根本没有连接。 或者它与表单的Click
事件相关联,但是您单击面板而不是表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.