gpt4 book ai didi

c# - 在 WPF 中显示 BitmapSource 不起作用

转载 作者:行者123 更新时间:2023-11-30 21:48:47 24 4
gpt4 key购买 nike

以下代码截取屏幕的一部分(在鼠标坐标处)并将其显示在 Image 控件中。

public partial class MainWindow : Window
{
Timer timer = new Timer(100);
public MainWindow()
{
InitializeComponent();

timer.Elapsed += Timer_Elapsed;
timer.Start();
}

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
viewerImage.Source = GetSnapAtMouseCoords((int)((Grid)viewerImage.Parent).ActualWidth, (int)((Grid)viewerImage.Parent).ActualHeight, System.Windows.Forms.Cursor.Position);
}

private BitmapSource GetSnapAtMouseCoords(int width, int height, System.Drawing.Point mousePosition)
{
IntPtr handle = IntPtr.Zero;

try
{

using (var screenBmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
{
using (var bmpGraphics = Graphics.FromImage(screenBmp))
{
bmpGraphics.CopyFromScreen(mousePosition.X, mousePosition.Y, 0, 0, screenBmp.Size);

handle = screenBmp.GetHbitmap();

var bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
handle,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());

return bs;
}
}
}

finally
{
DeleteObject(handle);
}
}
}

一切正常,直到我将图像源设置为 BitmapSource。不幸的是,图像永远不会在屏幕上呈现。

我认为这可能是因为我在 GUI 线程上创建了 BitmapSource...但我不太确定。

欢迎任何建议或想法。

最佳答案

实际上这是因为您在不同的线程上访问您的 GUI。您可以像这样包装初始调用:

Dispatcher.BeginInvoke(new Action(() =>
{
viewerImage.Source = GetSnapAtMouseCoords(
(int)((Grid)viewerImage.Parent).ActualWidth,
(int)((Grid)viewerImage.Parent).ActualHeight,
System.Windows.Forms.Cursor.Position);
}));

或者在后台线程中进行所有处理,只返回一个Frozen(线程安全)BitmapSource。您将悬停需要以不同方式传递 (int)((Grid)viewerImage.Parent).ActualWidth,因为它也由 UI 线程拥有。

bs.Freeze();

Dispatcher.BeginInvoke(new Action(() =>
{
viewerImage.Source = bs;
}));

关于c# - 在 WPF 中显示 BitmapSource 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37437514/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com