【问题标题】:WPF Image won't display BitmapSourceWPF 图像不会显示 BitmapSource
【发布时间】:2010-12-16 17:45:52
【问题描述】:

我刚开始使用 WPF 和 GDI,但无法显示图像。我的最终目标是构建类似暴露的东西。到目前为止,我将屏幕灰显,收集所有活动的 HWND,并捕获所有窗口的屏幕。目前,我有一个 Image 元素,我尝试为其设置源,但没有显示任何内容。

foreach (IntPtr hwnd in hwndlist)
{
    IntPtr windowhdc = GetDC((IntPtr) hwnd);
    IntPtr bmap = CreateBitmap(400, 400, 1, 32, null);
    IntPtr bitmaphdc = GetDC(bmap);
    BitBlt(bitmaphdc, 0, 0, System.Convert.ToInt32(this.Width), System.Convert.ToInt32(this.Height), windowhdc, 0, 0, TernaryRasterOperations.SRCCOPY);
    ReleaseDC(hwnd, windowhdc);
    BitmapSource bmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
    image1.Source = bmapSource;
    image1.BeginInit();
}

完整的代码在这里:
http://pastebin.com/m70af590 - 代码
http://pastebin.com/m38966750 - xaml

我知道我现在拥有它的方式对我正在尝试做的事情没有多大意义(运行循环并一遍又一遍地写入同一个图像),但我希望有一些东西最后那张图。

我已尝试对可见窗口的 HWND 进行硬编码,但仍然无法正常工作。

感谢您的帮助!

【问题讨论】:

    标签: c# wpf xaml gdi bitmapsource


    【解决方案1】:

    我认为使用 Memory DC 可以解决您的问题。为此,首先导入:

    [DllImport("gdi32.dll", EntryPoint = "CreateCompatibleDC")]
    public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
    
    [DllImport("gdi32.dll", EntryPoint = "SelectObject")]
    public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
    
    [DllImport("gdi32.dll",EntryPoint="DeleteDC")]
    public static extern IntPtr DeleteDC(IntPtr hDc);
    

    而不是这个:

    IntPtr bitmaphdc = GetDC(bmap);
    BitBlt(bitmaphdc, 0, 0, System.Convert.ToInt32(this.Width), System.Convert.ToInt32(this.Height), windowhdc, 0, 0, TernaryRasterOperations.SRCCOPY);
    

    这样做:

    IntPtr memdc = CreateCompatibleDC(windowhdc);
    SelectObject(memdc, bmap);
    
    BitBlt(memdc, 0, 0, System.Convert.ToInt32(this.Width), System.Convert.ToInt32(this.Height), windowhdc, 0, 0, TernaryRasterOperations.SRCCOPY);
    

    以后别忘了删除 Memort DC:

    DeleteDC(memdc);
    

    顺便说一句,你不需要image1.BeginInit();

    还要检查一下,您不需要枚举所有窗口。请改用 user32.dll 中的GetDesktopWindow 方法。

    【讨论】:

      猜你喜欢
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2011-09-19
      • 1970-01-01
      相关资源
      最近更新 更多