Dispose pattern for class with static methods using SystemEvents in WinForms control

109 Views Asked by At

I have a WinForms control in which some UI elements are drawn with static methods of an internal class - something like this:

internal class DrawUIElement
{
  public static void DrawArrow(Graphics g, Rectangle rect)
  {
    // Drawing something on the Graphics g
  }
}

Now I need to modify this class to support high-res screens. The improved version of the class will draw UI elements depending on the screen resolution. This implies I need to do some calculations based on the screen's current DPI and re-calculate them when the DPI changes. My intention is to use the SystemEvents.DisplaySettingsChanged event for that. I am going to add an event handler in the constructor of the DrawUIElement class and do all required recalculations when the DPI changes in the event handler:

static DrawUIElement()
{
    Microsoft.Win32.SystemEvents.DisplaySettingsChanged += SystemEvents_DisplaySettingsChanged;
}

private static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e)
{
    // Recalculate internal parameters based on the new screen DPI
}

This WinForms control already creates instances of some classes employing the similar SystemEvents.UserPreferenceChanged event. Those classes implement the Dispose() method from the IDisposable pattern to release references to the SystemEvents_UserPreferenceChanged event handler to avoid resource leaking when the form with the control is closed.

The question is: do I also need to add the Dispose() method to my DrawUIElements class that will detach my SystemEvents_DisplaySettingsChanged event handler from SystemEvents.DisplaySettingsChanged to avoid resource leaking or there is no need to worry about this in a class containing only static methods?

0

There are 0 best solutions below