private void Button_Click(object sender, RoutedEventArgs e) { Bitmap image = VisualToBitmapConverter.GetBitmap(border, (int)border.ActualWidth, (int)border.ActualHeight); image.Save(@"C:\YourPath\test.png"); }
private static async Task <BitmapSource> RenderAsync(System.Windows.Media.Brush brush, Rect helperWindowLocation, Size snapshotSize) { // Create a tmp window with its own hwnd to render it later var window = new Window { WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, ShowInTaskbar = false, Background = System.Windows.Media.Brushes.White }; window.Left = helperWindowLocation.X; window.Top = helperWindowLocation.Y; window.Width = helperWindowLocation.Width; window.Height = helperWindowLocation.Height; window.ShowActivated = false; var content = new Grid() { Background = brush }; RenderOptions.SetBitmapScalingMode(content, BitmapScalingMode.HighQuality); window.Content = content; var handle = new WindowInteropHelper(window).EnsureHandle(); window.Show(); // Make sure the tmp window is under our mainwindow to hide it SetWindowPos(handle, _HwndBottom, 0, 0, 0, 0, _SWP_NOMOVE | _SWP_NOSIZE | _SWP_NOACTIVATE); //Wait for the element to render //await popupChild.WaitForLoaded(); await window.WaitForFullyRendered(); ////Why we have to wait here fore the visualbrush to finish its lazy rendering Process? //// Todo: It seems like very complex uielements does not finish its rendering process within one renderloop //// Check https://stackoverflow.com/questions/2851236/rendertargetbitmap-resourced-visualbrush-incomplete-image // Async BitBlt the tmp Window var bitmapSourceT = await Task.Run(() => { Bitmap bitmap = VisualToBitmapConverter.GetBitmap(handle, (int)snapshotSize.Width, (int)snapshotSize.Height); var bitmapSource = new SharedBitmapSource(bitmap); bitmapSource.Freeze(); return(bitmapSource); }); // Close the Window window.Close(); return(bitmapSourceT); }