views:

23

answers:

1

Hey Guys

I'm playing around with Interops and I thought: "Hey let's code something that accesses the clipboard ..." so I googled and found some articles (yeah I'm doing it with WPF - .Net 3.5).

However the following method generates an error (as seen in the title) and throws a stackoverflow.

private void Window_SourceInitialized(object sender, EventArgs e)
{
    // Hook to Clipboard
    base.OnSourceInitialized(e);
    HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
    if (hwndSource != null)
    {
        installedHandle = hwndSource.Handle;
        viewerHandle = SetClipboardViewer(installedHandle);
        hwndSource.AddHook(new HwndSourceHook(this.hwndSourceHook));
    }
    // End Hook to Clipboard 
} 

I have (really) no idea what's going on there.

Any Ideas?

+2  A: 

Your problem is the call to base.OnSourceInitialized. You should call the base implementation when you're overriding the method, but it's not the case here : you're handling an event, not overriding a method.

Since the SourceInitialized event is raised by the OnSourceInitialized method, if you call OnSourceInitialized from the event, it will raise the event again. So you have an infinite recursion, which eventually causes a stack overflow.

So you have 2 options to fix the problem:

  • override OnSourceInitialized rather than handling the SourceInitialized event
  • remove the call to base.OnSourceInitialized
Thomas Levesque
Thanks, I was all wrapped up in Interops, didn't think of this one.
Dänu