0

my Question is how to "draw" on multiple labes. I have a form containing a matrix of labels. Now I want to click on one Label drag over some others and all these Labels should change the background color. I have a method which changes the color with the Click-Event, but I can't find an Event for this Problem. I also tried the Mous_Enter Event and checked if the left button was down, but it looks like, that the Event Trigger was stuck in the first label.

So at first I have this, where each number is in a different label: enter image description here

And then I want to "draw" on the labels, so that the Background Color changes and so I have something like the following: enter image description here

Daniel Müssig
  • 1,582
  • 1
  • 14
  • 26
  • When the mouse button gets down the mouse is bound the the control onto which the mousedown happens. You can then use its mousemove and check on which coordinates it does move. These will be __outside that control__, ie smaller than zero and/or greater than its size. So you will have to caculate where it is.. - Also did you consider using a Datagridview? – TaW Mar 26 '15 at 08:17
  • ..or you [loop over all controls](http://stackoverflow.com/questions/586479/is-there-a-quick-way-to-get-the-control-thats-under-the-mouse) – TaW Mar 26 '15 at 08:26

1 Answers1

2

Connect the MouseClick and MouseMove event of all your labels to the following event handler:

    private void MouseClickedOrMoved(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            ChangeLabelBackColor(this.PointToClient(MousePosition));
        }
    }

and add this function to your code:

    private void ChangeLabelBackColor(Point Location)
    {
        foreach (Label l in this.Controls.OfType<Label>()) {
            if (l.Bounds.Contains(Location))
            {
                l.BackColor = Color.Black;
            }
        }
    }
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • 1
    Beat me by 30 seconds. Darn. – TaW Mar 26 '15 at 08:25
  • Thank you very much. It works nearly perfect. I have my Labels in a FlowLayoutPanel and your Code draws one or two labels under the selected, do you have an idea? (I use flowLayoutPanel.Controls instead of Controls only since it doesn't works without it) – Daniel Müssig Mar 26 '15 at 09:15
  • 1
    yes. in this row: `ChangeLabelBackColor(this.PointToClient(MousePosition));` change the word `this` to your panel's name – Zohar Peled Mar 26 '15 at 09:18