I am using a NativeWindow
object to subclass an unmanaged window's message pump, with the purpose of intercepting its messages.
Code structure looks something like this (its psuedo C#, please excuse minor syntax problems):
class AppSubclass : Control {
class SpecialAppWndProc : NativeWindow {
protected override void WndProc(ref Message m) {
switch (m.msg) {
// do stuff
if (SpecialEvent != null) SpecialEvent(x);
}
base.WndProc(ref m);
}
public delegate void SpecialEventHandler(int Xstart);
public event SpecialEventHandler SpecialEvent;
~SpecialAppWndProc() {
DebugTrace("Help! Save me!");
}
}
private SpecialAppWndProc specialAppWndProc = new SpecialAppWndProc();
private void StartMonitoring() {
// do stuff
specialAppWndProc.AssignHandle(hWndUnmanagedWindow);
specialAppWndProc.SpecialEvent += new SpecialAppWndProc.SpecialEventHandler(specialAppWndProc_SpecialEvent);
}
/* ... event handler ... */
public AppSubClass() {
StartMonitoring();
}
}
Now, I thought that setting an event listener would be sufficient to keep the Garbage Collector at bay, if my object is dieing because of the GC. If it isn't, is it possible to trace how-and-why? I have never known .Net to just kill objects due to code bugs (exceptions and the occasional silent-failure seem to be the general gist of things) and I have no idea how or why the host app (my app is a COM server for unmanaged code) would have enough knowledge to kill my objects either.
Given that the object dies seemingly randomly (I haven't been able to pinpoint a certain set of events, only that it dies anywhere from less than a second to a few minutes after StartMonitoring() is called.
It would appear that HandleRef
might solve my woes, however I am unclear on how to use that in this context and I can't think of how to fit it in my code (other than maybe declaring one at the AppSubclass level and then assigning it the SpecialAppWndProc object.
So, how do I prevent my object from dieing before I am ready for it to die?