Add an event handler from other threads using BeginInvoke

G

Guest

I have a worker thread, and the thread needs to listen to WinForms Control's
SizeChanged event. Here's my code.

Control c = ...;
if (c.InvokeRequired) {
c.BeginInvoke(===don't know how to write here===);
} else {
c.SizeChanged += new EventHandler(this.OnOwnerSizeChanged);
}

I know I need to Invoke since my worker thread is not a UI thread. The
question is that, how could I write a C# code to create a delegate that adds
an event handler?

I tried:
c.BeginInvoke(new AddEventHandlerHandler(c.add_SizeChanged), new
EventHandler(this.OnOwnerSizeChanged));

But this doesn't compile.
 
N

Nicholas Paldino [.NET/C# MVP]

Koji,

First, you have to define the delegate, this will take one parameter of
type EventHandler.

public delegate void AddEventHandlerCallback(EventHandler handler);

Then, define the method.

public AddEventHandler(EventHandler handler)
{
// If null, then just get out.
if (handler == null)
// Get out.
return;

// Add the event.
c.SizeChanged += handler;

// That's all folks.
return;
}

Then, in your thread, you call invoke.
c.BeginInvoke(new AddEventHandlerCallback(AddEventHandler), new
object[]{new EventHandler(this.OnOwnerSizeChanged)});

Hope this helps.
 
G

Guest

So, what you are saying is that, basically, in C#, you cannot create a
delegate for get_, put_, add_, and remove_ accessors. Isn't this a problem?

I would like my code to work against any Control class, so I cannot add a
method to wrap these accessors.

It looks like you are saying I cannot do this in C#. I believe I can do this
in IL, so this is a C# limitation, correct?
 
G

Guest

Found solution, though it's not pretty.

private delegate IntPtr GetIntPtrDelegate();

Type type = target.GetType();
Delegate funcptr = Delegate.CreateDelegate(typeof(GetIntPtrDelegate),
target, "get_" + name);
target.Invoke(funcptr, new object[0]);

Shouldn't this be part of the language?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top