新しい背景を追加するたびにコードがメモリに蓄積されるという唯一の問題を除いて、スクリーンショットを別のアプリに送信し、WPF ウィンドウに表示する必要があるアプリがあります。
この問題を解決するにはどうすればよいですか?
ありがとう!
private void GetSnapshots(object state)
{
using (var socket=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(new IPEndPoint(IPAddress.Parse("10.0.0.9"), 8081));
while (Connected)
{
var lengthData = new byte[4];
var lengthBytesRead = 0;
while (lengthBytesRead < lengthData.Length)
{
var read = socket.Receive(lengthData, lengthBytesRead, lengthData.Length - lengthBytesRead, SocketFlags.None);
if (read == 0) return;
lengthBytesRead += read;
}
var length = BitConverter.ToInt32(lengthData, 0);
var imageData = new byte[length];
var imageBytesRead = 0;
while (imageBytesRead < imageData.Length)
{
var read = socket.Receive(imageData, imageBytesRead, imageData.Length - imageBytesRead, SocketFlags.None);
if (read == 0) return;
imageBytesRead += read;
}
using (var stream = new MemoryStream(imageData))
{
var bitmap = new Bitmap(stream);
Dispatcher.Invoke(new ImageCompleteDelegate(ImageComplete), new object[] { bitmap });
stream.Dispose();
bitmap.Dispose();
}
}
socket.Disconnect(false);
}
}
public static System.Windows.Media.Brush CreateBrushFromBitmap(Bitmap bmp)
{
return new ImageBrush(Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()));
}
private delegate void ImageCompleteDelegate(Bitmap bitmap);
private void ImageComplete(Bitmap bitmap)
{
if (_buffer != null)
{
_buffer = null;
}
_buffer = new Bitmap(bitmap);
bitmap.Dispose();
//ScreenShotG is a Grid Element inside the XAML
ScreenShotG.Background = CreateBrushFromBitmap(_buffer);
}