Exception in FromHdc()

At regular intervals I get an exception

while (true)
{
    try {
        FlashMessage("TEST\n" + "\ne1=" + e1.ToString(), font, Color.Black);
    }
    catch (Exception ex) {
        e1++; 
        Debug.WriteLine("FlashMessage() -> " + ex.Message);
    }
    Thread.Sleep(1000); c++;
}

static void FlashMessage(string txt, Font font, Color color) //+31.01.24
{
    var w = 240;
    var h = 160;
    var screen = Graphics.FromHdc(DisplayController.Hdc);
    var x = (screen.Width - w) / 2;
    var y = (screen.Height - h) / 2;
    var flags = Graphics.DrawTextAlignment.AlignmentCenter | Graphics.DrawTextAlignment.WordWrap;
    //var font = FontManager.GetFont(FontManager.FontType.droid_reg24); //Resources.GetFont(Resources.FontResources.roboto_condensed_20_full);
    var txt_size = screen.MeasureString(txt, font, new SizeF(w, h), new StringFormat() { Alignment = StringAlignment.Center });
    //_bmp = new Bitmap(screen.GetBitmap(x, y, w, h), w, h);
    //screen.Clear();
    screen.FillRectangle(new SolidBrush(Color.Yellow), x, y, w, h);
    screen.DrawTextInRect(txt, x, (screen.Height - (int)txt_size.Height) / 2, w, (int)txt_size.Height, flags, color, font);
    screen.DrawRectangle(new Pen(Color.Black), x, y, w, h);
    screen.Flush(x, y, w, h);
}

Failed allocation for 9606 blocks, 153696 bytes

#### Exception System.ArgumentException - 0xfd000000 (1) ####
#### Message: 
#### System.Drawing.Internal.Bitmap::.ctor [IP: 0000] ####
#### System.Drawing.Graphics::CreateSurface [IP: 0011] ####
#### System.Drawing.Graphics::.ctor [IP: 0006] ####
#### System.Drawing.Graphics::FromHdc [IP: 002d] ####
#### Tools.Display::FlashMessage [IP: 0016] ####
#### test_disp.Program::Main [IP: 002b] ####

FlashMessage() → Exception was thrown: System.ArgumentException

Try moving this block of code outside of the flash message method and out of your while loop:

var w = 240;
var h = 160;
var screen = Graphics.FromHdc(DisplayController.Hdc);
var x = (screen.Width - w) / 2;
var y = (screen.Height - h) / 2

This way it is called before entering your loop and instantiated once.

1 Like