Cannot obtain value of local or argument 'hwndSource' as it is not available at this instruction pointer
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);
hwn开发者_开发百科dSource.AddHook(new HwndSourceHook(this.hwndSourceHook));
}
// End Hook to Clipboard
}
I have (really) no idea what's going on there.
Any Ideas?
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 theSourceInitialized
event - remove the call to
base.OnSourceInitialized
精彩评论