CreateCompatibleDC(IntPtr.Zero) returns IntPtr.Zero RRS feed

  • Question

  • I have the following code for a class. This is the initialize of a class. 


         public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

                protected void initialize()
                if (_initialized)
                if (_hdc == IntPtr.Zero)
                _hdc = GDI32.CreateCompatibleDC(IntPtr.Zero);
                if (_hdc == IntPtr.Zero)
                throw new GDIException("Failed to create compatible device context.");
                if (_hFontOld == IntPtr.Zero)
                _hFont = FontSettings.GenerateHFont(_fontSetting, _hdc, _dpi, _forceFixedPitch);
                _hFontOld = GDI32.SelectObject(_hdc, _hFont);
                _initialized = true;

    This code in production works very well. But every 4hrs or so after some load on the server, GDI32.CreateCompatibleDC(IntPtr.Zero) returns IntPtr.Zero and the exception throw new GDIException("Failed to create compatible device context.") is thrown 

    How do I troubleshoot this problem. Could this be a memory leak? 
    I cannot make it happen on test or development.
    This is a .NEt application that references a 3rd party component. This code is part of their component. 
    Friday, August 9, 2019 10:03 PM

All replies

  • Probably you or third-party libary create too many objects. But resources are limited.

    Try limiting the lifetime of objects to a reasonable duration. Avoid creating of large amount of GDI objects. Usually such objects can be created before the usage, then freed.

    According to documentation, the unneeded DC can be destroyed with DeleteDC or DeleteObject. The font can be destroyed with DeleteObject, but you should also select the previous font using SelectObject.

    Saturday, August 10, 2019 6:40 AM
  • Hello fa6bc41f-9362-46545,

    1. Here are my suggestions on troubleshooting this issue :

    - Add in logging in your code so as to identify the number of times initialize() was called with _initialized  set to false.

    - Use a GDI resource monitoring tool alongside logging to monitor the GDI usage of your application.

    2. For GDI Resource Monitoring, see the answer given by RLWA32 in the following link : GDI resource monitoring


    Please visit my blog :

    Sunday, August 11, 2019 6:21 PM