Search code examples
c#.netwpfmousekeyhook

Equivalent to IsDisposed using c# wpf


I am working on a custom keycasting program for tut videos and I am using MouseKeyHook and I am using the example code found here: https://github.com/gmamaladze/globalmousekeyhook/blob/vNext/Demo/Main.cs to get the basic construction working.

As the example was intended for win forms I am having trouble with one line in particular. I have made everything work by omitting - if (IsDisposed) return; line 176.

How do i replicate this code for wpf?

 private void Log(string text)
    {
       if (IsDisposed) return;
        textBoxLog.AppendText(text);
        textBoxLog.ScrollToLine(textBoxLog.LineCount - 1);
    }

EDIT: This was not related to garbage collection it is because if the form is disposed textBoxLog will throw a ObjectDisposedException.


Solution

  • It's not for garbage collection, it is because if the form is disposed textBoxLog will throw a ObjectDisposedException if you try to call AppendText or ScrollToLine after the form has been disposed and Log gets called after the fact.

    WPF windows and controls are not disposable like winforms is, however if you want to recreate the behavior just override to the OnClosed method and set a flag.

    private bool _isClosed = false;   
    
    protected override void OnClosed(EventArgs e)
    {
        _isClosed = true;
        base.OnClosed(e);     
    }
    
    private void Log(string text)
    {
       if (_isClosed) return;
        textBoxLog.AppendText(text);
        textBoxLog.ScrollToLine(textBoxLog.LineCount - 1);
    }