I Have a WindowsService project.In this service I wanna render an UserControl but png file is empty.
for test i write the following code to export a TextBlock but result is an empty png file.
protected override void OnCustomCommand(int command)
{
Export();
base.OnCustomCommand(command);
}
private void Export()
{
var thread = new Thread(() =>
{
var grid = new Grid();
grid.Children.Add(new TextBlock() { Text = "ExportTest", FontSize = 60,
Background = Brushes.Red, Foreground = Brushes.Blue });
double widthg = grid.Width > 0 ? grid.Width : 1024;
double heightg = grid.Height > 0 ? grid.Height : 768;
grid.Measure(Size.Empty);
grid.Measure(new Size(widthg, heightg));
grid.Arrange(new Rect(0, 0, widthg, heightg));
grid.UpdateLayout();
Size size = new Size(widthg, heightg);
RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width,
(int)size.Height, 96, 96, PixelFormats.Pbgra32);
DrawingVisual drawingvisual = new DrawingVisual();
using (DrawingContext context = drawingvisual.RenderOpen())
{
context.DrawRectangle(new VisualBrush(grid), null, new Rect(new Point(),
size));
context.Close();
}
result.Render(drawingvisual);
using (var fs = new FileStream(@"..\ExportTest.png", FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(result));
encoder.Save(fs);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
Note: when i run the export function in wpf project, it works perfect.
there is my project:
http://www.mediafire.com/file/aij5sg4zx80yc73/ExportProject.rar
any body can help me?
What I have tried:
I Searched but found nothing. can any body help me?