Reputation: 115
So, I'm building a little app that has 118 buttons for clicking. It is a seat-chooser for an airplane. Instead of adding 118 buttons, i added an image and included 118 rectangles on it, positioning them correctly.
When the user clicks a rectangle, I can't seem to find a way to identify which seat was clicked... Is there a way to add a name field to the Rectangle class or any other way to solve this?
Upvotes: 0
Views: 899
Reputation: 81635
The Rectangle structure is sealed, so you can't inherit it.
But you can try just making your own class:
public class Seat {
private string _SeatKey;
private Rectangle _SeatRectangle;
public Seat(string seatKey, Rectangle seatRectangle) {
_SeatKey = seatKey;
_SeatRectangle = seatRectangle;
}
public string SeatKey {
get { return _SeatKey; }
}
public Rectangle SeatRectangle {
get { return _SeatRectangle; }
set { _SeatRectangle = value; }
}
}
Example:
private List<Seat> _Seats = new List<Seat>();
public Form1() {
InitializeComponent();
_Seats.Add(new Seat("1a", new Rectangle(10, 10, 10, 10)));
_Seats.Add(new Seat("2b", new Rectangle(20, 20, 10, 10)));
}
private void Form1_Paint(object sender, PaintEventArgs e) {
foreach (Seat seat in _Seats)
e.Graphics.FillRectangle(Brushes.Red, seat.SeatRectangle);
}
private void Form1_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
foreach (Seat seat in _Seats) {
if (seat.SeatRectangle.Contains(e.Location))
MessageBox.Show("Clicked on seat " + seat.SeatKey);
}
}
}
Upvotes: 1
Reputation: 4328
Bit dirty but you can use Cursor.X and Cursor.Y to get the mouse click location. If its going to run in fullscreen you could check the location of the rectangles.
Upvotes: 1
Reputation: 9060
Since airplanes can change and have a different number of seats, you can make your program more generic using just labels or buttons. 200 labels or button are not so much in reality, and it work with performances similar to draw text over an image or a panel in the Paint event.
However for your specific problem, you should get the MouseDown event and use X and Y coordinates to understand where the user clicked.
Upvotes: 1