0
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
        System.Drawing.Graphics formGraphics;
        formGraphics = this.CreateGraphics();
        for (int ii = 0; ii != (10); ii++)
        {
            for (int i = 0; i != (10); i++)
            {
                formGraphics.FillRectangle(myBrush, new Rectangle(i * 30, ii*30, 20, 20));
            }
        }
        myBrush.Dispose();
        formGraphics.Dispose();

I am trying to code minesweeper. I am basically trying to create a set of rectangles that a user will be able to click, but when I am trying to use the code above, all I have is a set of 10x10 rectangles that a user cannot interact with.

ClinsBER
  • 47
  • 8
  • IIRC you can't do that the way you would expect. See, if you have something like a panel or similar you could use their events. Since you are drawing on the form directly you would need to add a click event to the form itself and check for the location of the click and then calculate which field was clicked, – Twenty Jan 12 '20 at 12:29
  • 1
    Never use CreateGraphics(), use the Paint event. Minimize and restore the window to see why that is important. You *can* click such a rectangle, the form's MouseClick event fires. It tells you where you clicked with the e.X and e.Y properties. Mapping it back to a specific cell is straight-forward, divide them by 30. – Hans Passant Jan 12 '20 at 12:37
  • 1
    You can a class object that contains your Shapes references (the Rectangle shape, Color when not selected, Color when selected and so on). Then check whether a Cell/Shape has been clicked, with `var selectedShape = [MyRectanglesList].FirstOrDefault(shp => shp.Rectangle.Contains([The clickedPoint]))`. If `selectedShape != null`, then you have the clicked shape and you can change its *look* using its specific properties and re-draw only that shape. You need the Graphics object referenced in a **Paint event** (see the `PaintEventArgs.Graphics` object) to draw your shapes. – Jimi Jan 12 '20 at 13:32
  • [This](https://stackoverflow.com/questions/32919918/how-to-draw-line-and-select-it-in-panel/32920894?r=SearchResults&s=7|21.8949#32920894) should help – TaW Jan 12 '20 at 21:02
  • Still need an answer for this question? – Adrian Efford Jun 15 '20 at 14:34

0 Answers0