WPF图像将不显示的BitmapSource
-
20-09-2019 - |
题
我新的使用WPF和GDI,以及我在显示图像的麻烦。我的最终目标是建立东西暴露,等等。到目前为止,我中灰色的屏幕,收集所有的活动HWNDs,并捕获所有窗口的屏幕。现在,我有我尝试设置为源单个图像元素,却迟迟没有出现。
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,它仍然是行不通的。
感谢您的帮助!
解决方案
我想用一个内存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);
和BTW,你不需要image1.BeginInit();
。
另外要检查一下,你不需要枚举所有窗口。从USER32.DLL改用GetDesktopWindow
方法。
不隶属于 StackOverflow