Click here to Skip to main content
15,879,326 members

Font causes GDI leak in custom control

Kaizen202 asked:

Open original thread
I have created a custom control like below.

C#
public partial class TextBoxEx : TextBox
{
    public TextBoxEx()
    {
        InitializeComponent();
        Font = Utility.normalFont;
    }

    protected override void OnPaint(PaintEventArgs pe)
    {
        base.OnPaint(pe);
    }
}
    //A utility class to initialize font.   
    class Utility
    {
        
        internal static Font normalFont = new Font("Arial", 18);
    }


I have two forms Form1 and Form2. This TextBoxEx is added to Form2. I am showing Form2 when clicking a button in Form1.

Continuously showing and closing Form2 causes GDI leak in my application. After analysing with a GDI detection tool(Bear.exe), it is found that the Font causes GDI leak.

My question is,
1. Why the Font is not released even though Dispose() method of TextBoxEx is get called.(While closing Form2, Dispose() method of TextBoxEx will be invoked automatically).
2. How can I solve GDI leak caused by Font?.
(Font.Dispose() cannot be called in Dispose() method of TextBoxEx. Because it throws "Parameter is not valid" exception in the constructor).
Tags: C#, .NET, GDI, Windows Forms, Custom controls

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900