C# WPF图像赢得';t显示位图源

C# WPF图像赢得';t显示位图源,c#,wpf,xaml,gdi,bitmapsource,C#,Wpf,Xaml,Gdi,Bitmapsource,我刚开始使用WPF和GDI,但在显示图像时遇到了问题。我的最终目标是构建类似的东西。到目前为止,我将屏幕灰显,收集所有活动的HWD,并捕获所有窗口的屏幕。现在,我有一个图像元素,我试图为其设置源代码,但没有显示任何内容 foreach (IntPtr hwnd in hwndlist) { IntPtr windowhdc = GetDC((IntPtr) hwnd); IntPtr bmap = CreateBitmap(400, 400, 1, 32, null);

我刚开始使用WPF和GDI,但在显示图像时遇到了问题。我的最终目标是构建类似的东西。到目前为止,我将屏幕灰显,收集所有活动的HWD,并捕获所有窗口的屏幕。现在,我有一个图像元素,我试图为其设置源代码,但没有显示任何内容

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();
}
完整代码如下:
-代码
-xaml

我知道我现在的方式对我正在尝试做的事情没有多大意义(运行循环并一遍又一遍地向同一个图像写入内容),但我希望最终能在该图像上找到一些东西

我已经尝试过为一个可见窗口的HWND编码,但仍然不起作用


谢谢你的帮助

我认为使用内存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);
以后不要忘记删除备忘录DC:

DeleteDC(memdc);
顺便说一句,您不需要
image1.BeginInit()

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