大家好,這是我的第一個問題。 我有一些問題讓我的自定義創建的單元類正常工作的單擊事件。到現在爲止,它通知單元格被點擊的時間,但它只顯示最後一個單元格被點擊,即使你點擊了第一個單元格。這是我的代碼。對象(類Cell)上的自定義點擊事件只要點擊了最後一個單元格就會觸發
class Cell
{
public const int Width = 220;
public const int Height = Width;
public Point Position { get; set; }
public string Id { get; set; }
public delegate void ClickEvent(object o);
public event ClickEvent Click;
public Cell()
{
}
public void OnClick(Point p)
{
if (Click != null)
{
if (p.X - 220 < Position.X && p.X > 200 && p.Y - 220 < Position.Y && p.Y > 10)
{
Click(this);
}
}
}
public override string ToString() { return "Cell(" + row + "," + col + ")"; }
}
public partial class Form1 : Form
{
Grid myGrid;
Cell cell;
private Point userPoint;
Graphics g;
int x = 200;
int y = 20;
public Form1()
{
InitializeComponent();
myGrid = new Grid();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
userPoint = e.Location;
cell.OnClick(userPoint);
label1.Text = userPoint.ToString();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics;
DrawCrossingCells();
myGrid.DrawAllCrossings(g,imageList1);
}
private void DrawCrossingCells()
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 4; col++)
{
cell = new Cell(row,col);
g.DrawRectangle(new Pen(Color.Blue),x,y,Cell.Width,Cell.Height);
cell.Position = new Point(x, y);
cell.Id = (col.ToString() + row.ToString()).ToString();
x += 220;
cell.Click += cell_Click;
}
x = 200;
y += 220;
}
}
private void cell_Click(object sender)
{
Cell cc = (Cell)sender;
Crossing cross = new Crossing(cc.Id);
cross.Position = cc.Position;
myGrid.AddCrossing(cross);
MessageBox.Show(cc.Id);
}
}
的「在細胞內的點?」不知怎的,部分感覺錯了。嘗試使用矩形?看起來你正在對Point進行一些數學運算,最終把它放在別的地方,而不是你實際得到它的地方。 – TJennings
你的意思是在Cell類的Onclick方法中的邏輯?因爲我沒有得到你。 – Vla
我認爲'Onclick'中的邏輯應該是'if(p.X> Position.X && p.X Position.Y && p.Y
petelids