views:

82

answers:

4

I am adding an event handler like this:

theImage.MouseMove += new MouseEventHandler(theImage_MouseMove);

but in my application, this code gets run every time the page is shown, so I want to attach the event handler only once, but how can I tell if a handler has been set yet or not, something like this:

if(theImage.MouseMove == null) //error
    theImage.MouseMove += new MouseEventHandler(theImage_MouseMove);
+1  A: 

I might me missing something, but if you just want to make sure that the handle is only called once, why don't you use -= before adding it. Something like this:

public static void Main(string[] args)
{
    var timer = new Timer(1000);

    timer.Elapsed -= new ElapsedEventHandler(timer_Elapsed);
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    timer.Elapsed -= new ElapsedEventHandler(timer_Elapsed);
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

    timer.Start();

    System.Threading.Thread.Sleep(4000);
}

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("Hit!");
}

The handler will only run once every second.

João Angelo
+1  A: 

You can shorten it down if you only want to attach once:

theImage.MouseMove -= theImage_MouseMove; //If it wasn't attached, doesn't matter
theImage.MouseMove += theImage_MouseMove;
Nick Craver
A: 
theImage.MouseMove.GetInvocationList().Length
UshaP
This doesn't work: http://stackoverflow.com/questions/1129517/c-how-to-find-if-an-event-is-hooked-up/1129530#1129530
Jason Punyon
for me it returns 3 (but didn't test it with mousemove)public static EventHandler ee; static void Main(string[] args) { ee += (s, e) => { }; ee += (s, e) => { }; ee += (s, e) => { }; Console.WriteLine(ee.GetInvocationList().Count()); Console.Read(); }
UshaP
That's because you're working directly on the ee delegate, not an event published by another class.
Jason Punyon
Well that's not true !! (sorry for the indentation, don't know how to make it)class Program { static void Main(string[] args) { Class1 mc = new Class1(); mc.ee += (s, e) => { }; mc.ee += (s, e) => { }; mc.ee += (s, e) => { }; Console.WriteLine(mc.ee.GetInvocationList().Count()); Console.Read(); } } class Class1 { public EventHandler ee; }but onmouse over is event and not delegate this is why you don't have GetInvocationList
UshaP
+1  A: 

I'm not sure if this is the best solution, but the way I usually do this is to simply use an unsubscribe before the subscribe.

If you do something like:

TheImage.MouseMove -= new MouseEventHandler(theImage_MouseMove);
TheImage.MouseMove += new MouseEventHandler(theImage_MouseMove);

It will only ever get added once. If it doesn't already exist (the first time it's triggered), the -= doesn't hurt anything if it hasn't been subscribed to previously.

NebuSoft