I have InkCanvas int Grid and I want render Grid to PNG file. My code works. My OS is Windows. But If I click switch account (user) on Windows before rendering (I added Task.Delay for that) the PNG file will be empty. Why is this happening? How to fix it?
My code:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800"
ResizeMode="NoResize">
<Grid
Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Row="0"
Content="RenderTargetBitmap"
HorizontalAlignment="Center"
Margin="0"
VerticalAlignment="Top"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
FontSize="14"
FontWeight="SemiBold"
FontStyle="Normal"/>
<Border Grid.Row="1"
BorderThickness="0,0,0,1"
BorderBrush="Black"/>
<Grid Grid.Row="2" Name="drawingGrid">
<InkCanvas
EditingMode="Ink"
Background="White" />
</Grid>
<Border Grid.Row="3"
BorderThickness="0,0,0,1"
BorderBrush="Black"/>
<Button Grid.Row="4"
Content="Save to bitmap ..."
Click="btnSaveToBitmap_Click"
Height="23"
Width="100"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Margin="0,10,50,10"/>
</Grid>
</Window>
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void btnSaveToBitmap_Click(object sender, RoutedEventArgs e)
{
string fileName = $"test.png";
await Task.Delay(5000);
saveControlImage(drawingGrid, (int)drawingGrid.ActualWidth, (int)drawingGrid.ActualHeight, fileName);
}
private void saveControlImage(Visual element, int imageWidth, int imageHeight, string pathToOutputFile)
{
var elementBitmap = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
elementBitmap.Render(element);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(elementBitmap));
using (var imageFile = new FileStream(pathToOutputFile, FileMode.Create, FileAccess.Write))
{
encoder.Save(imageFile);
imageFile.Flush();
imageFile.Close();
}
}
}
}
Hi, @Hui Liu-MSFT . I'am using Windows 11, but I tried Windows 10. The result is the same. Code good works. I want to understand what happens to applications in Windows when changing the user? Thank you for for trying to help.