GDI calls do not work in WPF application when called the 1st time

0

The following test function

  1. works when called form a console application
  2. does not work when called the 1st time in a WPF application. A .png file of size 200 x 200 is created with "empty" pixels (ARGB=0x00000000).
  3. works when called a 2nd time (just one the next line) in WPF application
  4. works when called from a different thread

(Pls do not discuss why using GDI here.)

using System.Drawing;
...
class SomeClass
{
    ...
    public void Test(string name)
    {
        using (var bmp = new Bitmap(200, 200))
        {
            using (var gr = Graphics.FromImage(bmp))
            {
                gr.FillRectangle(Brushes.Green, 0, 0, bmp.Width, bmp.Height);
                bmp.Save(Path.Combine(@"C:\Temp\" + name + ".png"));
            }
        }
    }
}

Cases 2. and 3. are called from a (WPF) MenuItem.Command being executed. Case 4 is also called during MenuItem.Command being executed but delegates to the thread pool (ThreadPool.QueueUserWorkItem(...)) for testing purpose.

The problem seems not to be the Save(..) method. Looks like the drawing method(s) (e.g. FillRectangle) of the Graphics do not work as expected (the Brushes look fine).

c#
wpf
gdi+
asked on Stack Overflow Aug 29, 2019 by user2261015

1 Answer

0

Well, I cannot anwer my question but I can describe my workaround: Instead of directly calling Test(...) delegating it to the dispatcher seems to help.

Dispatcher.CurrentDispatcher.Invoke(() => { Test("SomeName"); });
answered on Stack Overflow Sep 4, 2019 by user2261015

User contributions licensed under CC BY-SA 3.0