473,699 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Connecting an event handler in one class and disconnecting it in a different class.

In my code, class A instanciates classes B and C.

I would like class B to connect an event handler to a method in class A, and
for class C to disconnect that event handler.

I think I've done too much thinking, and now I'm even more confused as to
how to accomplish this as when I started.

Any help will be appreciated.
Nov 15 '05 #1
10 3488
Hi,

Thanks for posting. The following code is for your reference:

using System;

public delegate void ADelegate();

public class A
{
public static void Main(string[] args)
{
B b = new B();
ADelegate d = new ADelegate(AMeth od);
b.AEvent += d;
C c = new C();
c.RemoveDelegat eFromB(d, b);
}

public static void AMethod()
{
Console.WriteLi ne("A method");
}
}

public class B
{
public event ADelegate AEvent;
public void RaiseAEvent()
{
if (AEvent != null)
{
AEvent();
}
}
}

public class C
{
public void RemoveDelegateF romB(ADelegate d, B b)
{
b.AEvent -= d;
}
}

I hope this helps. If there is anything else I can help with, please feel
free to post here.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #2
Assuming that ClassB and ClassC have a reference to ClassA then there should
be no Problem in doing this.

class ClassA
{
ClassB cl_B=null;
ClassC cl_C=null;
Panel pn_Panel=null
public ClassA()
{
pn_Panel = new Panel();
cl_B = new ClassB(this);
cl_C = new ClassC(this);
}
public void Dispose()
{
if (cl_C != null)
cl_C=null;
}
protected virtual void OnMouseDown(obj ect
sender,System.W indows.Forms.Mo useEventArgs e)
{
if (i_DragDrop == 0)
{
OnDragDrop(e.X, e.Y); // Do what must be done and check the results, set
i_DragDrop if something found
} // if (i_DragDrop == 0)
} // protected override void OnMouseDown(obj ect
sender,System.W indows.Forms.Mo useEventArgs e)
} // Class A

class ClassB
{
public ClassB(ClassA cl_A)
{
cl_A.pn_Panel.M ouseDown += new
System.Windows. Forms.MouseEven tHandler(cl_A.O nMouseDown);
}
} // ClassB
class ClassC
{
ClassA cl_A=null;
public ClassC(ClassA clA)
{
cl_A = clA;
}
public void Dispose()
{
if (cl_A != null)
cl_A.pn_Panel.M ouseDown -= new
System.Windows. Forms.MouseEven tHandler(cl_A.O nMouseDown);
}
} // ClassC

This should work.
This works in my Projects where a ClassA calls ClassB assuming that ClassB
will clean up what it has done in ClassA when closing.
Note : since ClassA is only needed in the Construction of ClassB here, it is
not saved to a Class Field as in ClassC.

Mark Johnson, Berlin Germany
mj*****@mj10777 .de

"SunshineGi rl" <bl**@blah.co m> schrieb im Newsbeitrag
news:10******** *****@corp.supe rnews.com...
In my code, class A instanciates classes B and C.

I would like class B to connect an event handler to a method in class A, and for class C to disconnect that event handler.

I think I've done too much thinking, and now I'm even more confused as to
how to accomplish this as when I started.

Any help will be appreciated.

Nov 15 '05 #3
Not quite.

Class A must hold the code for the event.
Class B must connect an event handler (+=), not raise the event.
Class C must disconnect the event handler (-=).

This is an already running application to which I'm trying to add
functionality. Class B uses Windows instrumentation to receive a
notification when the user launches an application. Class C uses Windows
instrumentation to receive a notification when the user terminates an
application. Class A instanciates both classes B and C. Classes B and C
don't know about each other.

The application currently monitors when the user has launched or terminated
applications. I'm trying to add the following functionality.

Whenever class B receives notification that Internet Explorer has launched,
it needs to connect the BeforeNavigate2 event handler to a method in class A
(so class B must do the += thing: ie.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(this. ie_BeforeNaviga t
e2). Whenever class C receives notification that Internet Explorer has been
terminated, it needs to disconnect the BeforeNavigate2 event handler (so
class C must do the -= thing: ie.BeforeNaviga te2 -= new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(this. ie_BeforeNaviga t
e2).

"Felix Wang" <v-*****@online.mi crosoft.com> wrote in message
news:sT******** *****@cpmsftngx a07.phx.gbl...
Hi,

Thanks for posting. The following code is for your reference:

using System;

public delegate void ADelegate();

public class A
{
public static void Main(string[] args)
{
B b = new B();
ADelegate d = new ADelegate(AMeth od);
b.AEvent += d;
C c = new C();
c.RemoveDelegat eFromB(d, b);
}

public static void AMethod()
{
Console.WriteLi ne("A method");
}
}

public class B
{
public event ADelegate AEvent;
public void RaiseAEvent()
{
if (AEvent != null)
{
AEvent();
}
}
}

public class C
{
public void RemoveDelegateF romB(ADelegate d, B b)
{
b.AEvent -= d;
}
}

I hope this helps. If there is anything else I can help with, please feel
free to post here.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #4
Hello,

Thanks for your update.

I would like to ask a question. What is the object that exposes the event
"BeforeNavigate 2" and how do you get a reference to it? If we can get the
reference (e.g. named "o") successfully, we can simply call
"o.BeforeNaviga te2 += " in class B and "o.BeforeNaviga te2 -= " in class C.

In addition, since the method for the event is defined in class A, we
cannot use "this" in class B and class C. If we define the method as
static, we can use "o.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(A.ie_ BeforeNavigate2 )
". If the method is non-static, we need to pass a reference to A into B or
simply create a new A object, so that the method can be accessed.

I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #5
I should have thought of that.

Thanks for the response.
"Mark Johnson" <mj*****@mj1077 7.de> wrote in message
news:40******** **************@ newsread2.arcor-online.net...
Assuming that ClassB and ClassC have a reference to ClassA then there should be no Problem in doing this.

class ClassA
{
ClassB cl_B=null;
ClassC cl_C=null;
Panel pn_Panel=null
public ClassA()
{
pn_Panel = new Panel();
cl_B = new ClassB(this);
cl_C = new ClassC(this);
}
public void Dispose()
{
if (cl_C != null)
cl_C=null;
}
protected virtual void OnMouseDown(obj ect
sender,System.W indows.Forms.Mo useEventArgs e)
{
if (i_DragDrop == 0)
{
OnDragDrop(e.X, e.Y); // Do what must be done and check the results, set i_DragDrop if something found
} // if (i_DragDrop == 0)
} // protected override void OnMouseDown(obj ect
sender,System.W indows.Forms.Mo useEventArgs e)
} // Class A

class ClassB
{
public ClassB(ClassA cl_A)
{
cl_A.pn_Panel.M ouseDown += new
System.Windows. Forms.MouseEven tHandler(cl_A.O nMouseDown);
}
} // ClassB
class ClassC
{
ClassA cl_A=null;
public ClassC(ClassA clA)
{
cl_A = clA;
}
public void Dispose()
{
if (cl_A != null)
cl_A.pn_Panel.M ouseDown -= new
System.Windows. Forms.MouseEven tHandler(cl_A.O nMouseDown);
}
} // ClassC

This should work.
This works in my Projects where a ClassA calls ClassB assuming that ClassB will clean up what it has done in ClassA when closing.
Note : since ClassA is only needed in the Construction of ClassB here, it is not saved to a Class Field as in ClassC.

Mark Johnson, Berlin Germany
mj*****@mj10777 .de

"SunshineGi rl" <bl**@blah.co m> schrieb im Newsbeitrag
news:10******** *****@corp.supe rnews.com...
In my code, class A instanciates classes B and C.

I would like class B to connect an event handler to a method in class A,

and
for class C to disconnect that event handler.

I think I've done too much thinking, and now I'm even more confused as to how to accomplish this as when I started.

Any help will be appreciated.


Nov 15 '05 #6
The object that exposes the BeforeNavigate2 event is the Internet Explorer
ShellWindows interface.

Here is that part of the code that connects the event handler. This is from
a Windows app and it works. Now it must be in class B):
private static SHDocVw.ShellWi ndows shellWindows = new
SHDocVw.ShellWi ndowsClass();

foreach(SHDocVw .InternetExplor er ie in shellWindows)
ie.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(this. ie_BeforeNaviga t
e2);

This is the event handler (that must be in class A):
public void ie_BeforeNaviga te2(object pDisp , ref object url, ref object
Flags, ref object TargetFrameName , ref object PostData, ref object
Headers, ref bool Cancel)
{
MessageBox.Show ("BeforeNavigat e2: " + url.ToString()) ;
}

Thank you for your help.
"Felix Wang" <v-*****@online.mi crosoft.com> wrote in message
news:Qz******** ******@cpmsftng xa07.phx.gbl...
Hello,

Thanks for your update.

I would like to ask a question. What is the object that exposes the event
"BeforeNavigate 2" and how do you get a reference to it? If we can get the
reference (e.g. named "o") successfully, we can simply call
"o.BeforeNaviga te2 += " in class B and "o.BeforeNaviga te2 -= " in class C.

In addition, since the method for the event is defined in class A, we
cannot use "this" in class B and class C. If we define the method as
static, we can use "o.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(A.ie_ BeforeNavigate2 ) ". If the method is non-static, we need to pass a reference to A into B or
simply create a new A object, so that the method can be accessed.

I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #7
Here's how far I got. But it doesn't work. Class B never enters the foreach loop.

ClassA:
public static SHDocVw.ShellWi ndows shellWindows = null;

public void ie_BeforeNaviga te2(object disp, ref object url, ref object flags, ref object targetFrameName , ref object postData, ref object headers, ref bool cancel)
{
MessageBox.Show ("BeforeNavigat e2: " + url.ToString()) ;
}

ClassB:
private ClassA classA = null;

in the constructor:
ClassA.shellWin dows = new SHDocVw.ShellWi ndowsClass();
foreach(SHDocVw .InternetExplor er ie in ClassA.shellWin dows)
ie.BeforeNaviga te2 += new SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(class A.ie_BeforeNavi gate2);

ClassC:
private ClassA classA = null;

in the constructor:
ClassA.shellWin dows = new SHDocVw.ShellWi ndowsClass();
foreach(SHDocVw .InternetExplor er ie in ClassA.shellWin dows)
ie.BeforeNaviga te2 -= new SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(class A.ie_BeforeNavi gate2);


"SunshineGi rl" <bl**@blah.co m> wrote in message news:10******** *****@corp.supe rnews.com...
The object that exposes the BeforeNavigate2 event is the Internet Explorer
ShellWindows interface.

Here is that part of the code that connects the event handler. This is from
a Windows app and it works. Now it must be in class B):
private static SHDocVw.ShellWi ndows shellWindows = new
SHDocVw.ShellWi ndowsClass();

foreach(SHDocVw .InternetExplor er ie in shellWindows)
ie.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(this. ie_BeforeNaviga t
e2);

This is the event handler (that must be in class A):
public void ie_BeforeNaviga te2(object pDisp , ref object url, ref object
Flags, ref object TargetFrameName , ref object PostData, ref object
Headers, ref bool Cancel)
{
MessageBox.Show ("BeforeNavigat e2: " + url.ToString()) ;
}

Thank you for your help.


"Felix Wang" <v-*****@online.mi crosoft.com> wrote in message
news:Qz******** ******@cpmsftng xa07.phx.gbl...
Hello,

Thanks for your update.

I would like to ask a question. What is the object that exposes the event
"BeforeNavigate 2" and how do you get a reference to it? If we can get the
reference (e.g. named "o") successfully, we can simply call
"o.BeforeNaviga te2 += " in class B and "o.BeforeNaviga te2 -= " in class C.

In addition, since the method for the event is defined in class A, we
cannot use "this" in class B and class C. If we define the method as
static, we can use "o.BeforeNaviga te2 += new

SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(A.ie_ BeforeNavigate2 )
". If the method is non-static, we need to pass a reference to A into B or
simply create a new A object, so that the method can be accessed.

I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.


Nov 15 '05 #8
Hello,

Thanks for your update. Let's try the following:

ClassA:
public static SHDocVw.ShellWi ndows shellWindows = new
SHDocVw.ShellWi ndowsClass();

public static void ie_BeforeNaviga te2(object disp, ref object url, ref
object flags, ref object targetFrameName , ref object postData, ref object
headers, ref bool cancel)
{
MessageBox.Show ("BeforeNavigat e2: " + url.ToString()) ;
}

ClassB:

in the constructor

foreach(SHDocVw .InternetExplor er ie in ClassA.shellWin dows)
ie.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(Class A.ie_BeforeNavi g
ate2);

ClassC:

in the constructor

foreach(SHDocVw .InternetExplor er ie in ClassA.shellWin dows)
ie.BeforeNaviga te2 -= new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(Class A.ie_BeforeNavi g
ate2);

Since the "shellWindo ws" is a static member, we can access it from both
ClassB and ClassC. We only need to "new" it once in ClassA. I have not
tested the code with IE. But from C# language's perspective, it should
work. I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #9
Thanks. That worked in a Windows application. However, I can't get it to
work inside a Windows service, which is what I want. I get the following
exception when I run the line "shellWindo ws = new
SHDocVw.ShellWi ndowsClass();":

COM object with CLSID {9BA05972-F6A8-11CF-A442-00A0C90A8F39} is either not
valid or not registered.

I know that this CLSID belongs to ShellWindows.

Any ideas?

Thanks again.
"Felix Wang" <v-*****@online.mi crosoft.com> wrote in message
news:Uw******** ******@cpmsftng xa08.phx.gbl...
Hello,

Thanks for your update. Let's try the following:

ClassA:
public static SHDocVw.ShellWi ndows shellWindows = new
SHDocVw.ShellWi ndowsClass();

public static void ie_BeforeNaviga te2(object disp, ref object url, ref
object flags, ref object targetFrameName , ref object postData, ref object
headers, ref bool cancel)
{
MessageBox.Show ("BeforeNavigat e2: " + url.ToString()) ;
}

ClassB:

in the constructor

foreach(SHDocVw .InternetExplor er ie in ClassA.shellWin dows)
ie.BeforeNaviga te2 += new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(Class A.ie_BeforeNavi g ate2);

ClassC:

in the constructor

foreach(SHDocVw .InternetExplor er ie in ClassA.shellWin dows)
ie.BeforeNaviga te2 -= new
SHDocVw.DWebBro wserEvents2_Bef oreNavigate2Eve ntHandler(Class A.ie_BeforeNavi g ate2);

Since the "shellWindo ws" is a static member, we can access it from both
ClassB and ClassC. We only need to "new" it once in ClassA. I have not
tested the code with IE. But from C# language's perspective, it should
work. I hope this helps.

Regards,

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
2882
by: Christopher W. Douglas | last post by:
I am writing a VB.NET application in Visual Studio 2003. I have written a method that handles several events, such as closing a form and changing the visible status of a form. I have some code that applies to all these events, but I need to have specific code execute when the form closes. The properties for this method are sender (the originator) and e (event arguments). I know how to get typeof (sender) to determine what form or...
8
6084
by: Mark | last post by:
Hi, I'm looking for some ideas on how to build a very simple Event processing framework in my C++ app. Here is a quick background ... I'm building a multithreaded app in C++ (on Linux) that uses message queues to pass pointers to Events between threads. In my app there are simple events that can be defined using an enum (for example an event called NETWORK_TIMEOUT) and more complex events that contain data (for example an event called...
4
1979
by: Claudio Jolowicz | last post by:
I am trying to find a solution to the following design problem (code at the bottom): We are implementing a trader agent that can trade with other traders on an electronical trading platform. To make the trader more extensible, we have defined a strategy interface and implemented this interface for different trading strategies. The problem relates to how to connect the trader and the strategy. The problem is tricky because the strategy...
3
3642
by: R Millman | last post by:
under ASP.NET, single stepping in debug mode appears not to stop within event procedures. i.e. 1) Create web page with submit button and event procedure for the click event in the code behind page, 2) Breakpoint in the Page_Load, 3) debug the web page and click the submit button, 4) "step into" under debug several times, 5) The debugger does not stop at any of the statements in the click event handler. A breakpoint is needed in each...
13
3504
by: Charles Law | last post by:
Mr "yEaH rIgHt" posted the following link about a week ago in answer to my question about removing event handlers. > http://www.vbinfozine.com/t_bindevt.shtml Following on from that post, the following issues still exist. The article shows how to find methods on a receiver that match the pattern OnXXXX given the sender. It loops through the sender events and tries to get methods from the receiver that match the pattern. For each one...
41
4302
by: JohnR | last post by:
In it's simplest form, assume that I have created a usercontrol, WSToolBarButton that contains a button. I would like to eventually create copies of WSToolBarButton dynamically at run time based on some initialization information obtained elsewhere. Basically, I'm going to create my own dynamic toolbar where the toolbarbuttons can change. I'm not using the VB toolbar because of limitations in changing things like backcolor (I can't get...
5
3858
by: james | last post by:
Hello, I am having a little trouble creating an event handler for a context menu toolstripmenuitem. I've seen various tutorials and so on, but I keep getting a bit stuck! So far I have a second class defining the eventargs I want to use: public class ApptEventArgs : EventArgs{ public int ApptUID; public String ApptOp;
9
2469
by: jeff | last post by:
New VB user...developer... Situation...simplified... - I want to wrap a pre and post event around a system generated where the pre-event will always execute before the system event and the post event will always execuate after the system is completed... - I want to wrap this functionality in a framework, so I could possibly have 3 or 4 levels of inherited objects that need to have these pre / post events executed before and after the...
8
36129
by: hoofbeats95 | last post by:
I don't think this should be this complicated, but I can't figure it out. I've worked with C# for several years now, but in a web environment, not with windows form. I have a form with a query button on it. If the query returns multiple results, a new window is opened with a grid containing the results. When the user double clicks on the desired row in the grid, I want the first form to populate with the correct data. I don't know how...
0
8686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8911
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7748
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6533
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4375
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3057
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2345
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2009
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.