这个简单的程序不起作用,图像不会出现在窗口中。
namespace ClipBoardTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CopyButton_Click(object sender, RoutedEventArgs e)
{
if (Clipboard.ContainsImage())
{
ImageUIElement.Source = Clipboard.GetImage();
Console.WriteLine("Clipboard copied to UIElement");
}
else
{
Console.WriteLine("No image in Clipboard");
}
}
}
}
输出是“剪贴板复制到UIElement”,但图像不会出现在窗口中。
XAML:
<Window x:Class="ClipBoardTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="CopyButton" Content="Copy" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Click="CopyButton_Click"/>
<Image x:Name="ImageUIElement" Margin="90,10,10,10"/>
</Grid>
</Window>
是否有人理解,出了什么问题?
答案 0 :(得分:5)
使用 Clipboard.GetDataObject
获取位图并将其转换为bitmapSource。此外,请注意 Bitmap.GetHbitmap()
会泄漏内存,除非您在其上调用DeleteObject。
因此,正确的解决方案是在使用后处置IntPtr。在类级别声明方法并从代码中使用它:
// at class level
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
if (Clipboard.ContainsImage())
{
IDataObject clipboardData = Clipboard.GetDataObject();
if (clipboardData != null)
{
if (clipboardData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
{
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)clipboardData.GetData(System.Windows.Forms.DataFormats.Bitmap);
IntPtr hBitmap = bitmap.GetHbitmap();
try
{
ImageUIElement.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
Console.WriteLine("Clipboard copied to UIElement");
}
finally
{
DeleteObject(hBitmap)
}
}
}
}
来源 - MSDN和Memory leak in Bitmap。
答案 1 :(得分:1)
现在工作正常。
if (Clipboard.ContainsImage())
{
// ImageUIElement.Source = Clipboard.GetImage(); // does not work
System.Windows.Forms.IDataObject clipboardData = System.Windows.Forms.Clipboard.GetDataObject();
if (clipboardData != null)
{
if (clipboardData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
{
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)clipboardData.GetData(System.Windows.Forms.DataFormats.Bitmap);
ImageUIElement.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());
Console.WriteLine("Clipboard copied to UIElement");
}
}
}
答案 2 :(得分:1)
Visual Studio 2019,针对.NET Core 3.1的WPF C#项目,以下工作原理(或者至少对我有用):
scipy
其中:
myImage.Source = GetImageFromClipBoard();