Sean Missingham
Sean Missingham

Reputation: 938

Listening for events only under certain circumstance

I'm after some opinions / advice as I'm rather new to event-driven programming and C# having come from web development origins.

I'm currently making a program in C# / Winforms, with a series of SplitContainer controls on the main form. I want to allow the user to effectively be able to select a group of them, say any 3 out of 8 (not limited to that). To start selecting them, the user will click a button and the program will go into a selecting mode, and at that time, if the user clicks on a control, the color of it will change indicating that it is selected.

At this stage, I have made it work fine, but I feel it's not very efficient in its detection of MouseMove events. I've bound a MouseMove event to the SplitContainer, and inside that event, the program detects whether we're in selecting mode. If so, and the user clicks, change the color. If not in selecting mode, then it wont do anything.

My worry is that every time the user moves their cursor over the control, this event is fired and it detects whether selecting mode is enabled. I feel like this should be the other way around, that is; only in selecting mode is such an event even listened to.

Here are some cut-outs to explain what I've got at the moment.

public bool selectingMode = false;

public Form(){
    SplitContainer split = new SplitContainer();
    split.MouseMove += new MouseEventHandler(MouseMoved);
    this.Controls.Add(split);
}

void MouseMoved(object sender, MouseEventArgs e){
    if(selectingMode){
        //change color of split
    }
}

As mentioned, that MouseMoved() method is triggered every time the user moves their cursor over that control, and then it only actions something if it's in selectingMode. Is there any way to reverse this? Only trigger that event if in selectingMode?

If I'm worrying about something that doesn't really matter, are you able to explain why? It seems like poor practice and that it would be using system resources (however little), especially considering that the vast majority of the time using this program will be spent with the cursor inside this box.

I appreciate and input, thanks! Sean

Upvotes: 0

Views: 49

Answers (2)

Fratyx
Fratyx

Reputation: 5797

Implement the selectingMode as property and put in the setter a split.MouseMove += new MouseEventHandler(MouseMoved); or split.MouseMove -= new MouseEventHandler(MouseMoved); depending on true or false.

Besides I don't think this change is necessary for performance reasons.

Upvotes: 1

DevEstacion
DevEstacion

Reputation: 1977

You may want to use a different event that satisfies your condition:

SplitContainer Class: MSDN SplitContainer Event: OnMouseClick

try subscribing to that event if you want it to be fired on click only, also, if you want to unsubscribe to an event, use the -= tag.

Upvotes: 1

Related Questions