在WPF中显示BitmapSource无法正常工作

时间:2016-05-25 12:42:14

标签: c# wpf

以下代码拍摄部分屏幕的快照(在鼠标坐标处),并应在图像控件中显示。

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 ......但我不太确定。

欢迎任何建议或想法。

1 个答案:

答案 0 :(得分:3)

实际上是因为您在不同的线程上访问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;
}));